原文: https://howtodoinjava.com/java/io/how-to-copy-directories-in-java/

要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用以下代码,该代码使用递归遍历目录结构,然后使用Files.copy()函数复制文件。

目录复制示例源代码

在此示例中,我将c:\temp下的所有子目录和文件复制到新位置c:\tempNew

  1. package com.howtodoinjava.examples.io;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.StandardCopyOption;
  6. public class DirectoryCopyExample
  7. {
  8. public static void main(String[] args) throws IOException
  9. {
  10. //Source directory which you want to copy to new location
  11. File sourceFolder = new File("c:\\temp");
  12. //Target directory where files should be copied
  13. File destinationFolder = new File("c:\\tempNew");
  14. //Call Copy function
  15. copyFolder(sourceFolder, destinationFolder);
  16. }
  17. /**
  18. * This function recursively copy all the sub folder and files from sourceFolder to destinationFolder
  19. * */
  20. private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
  21. {
  22. //Check if sourceFolder is a directory or file
  23. //If sourceFolder is file; then copy the file directly to new location
  24. if (sourceFolder.isDirectory())
  25. {
  26. //Verify if destinationFolder is already present; If not then create it
  27. if (!destinationFolder.exists())
  28. {
  29. destinationFolder.mkdir();
  30. System.out.println("Directory created :: " + destinationFolder);
  31. }
  32. //Get all files from source directory
  33. String files[] = sourceFolder.list();
  34. //Iterate over all files and copy them to destinationFolder one by one
  35. for (String file : files)
  36. {
  37. File srcFile = new File(sourceFolder, file);
  38. File destFile = new File(destinationFolder, file);
  39. //Recursive function call
  40. copyFolder(srcFile, destFile);
  41. }
  42. }
  43. else
  44. {
  45. //Copy the file content from one place to another
  46. Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
  47. System.out.println("File copied :: " + destinationFolder);
  48. }
  49. }
  50. }
  51. Output:
  52. Directory created :: c:\tempNew
  53. File copied :: c:\tempNew\testcopied.txt
  54. File copied :: c:\tempNew\testoriginal.txt
  55. File copied :: c:\tempNew\testOut.txt

使用Files.copy()方法,可以复制目录。 但是,目录内的文件不会被复制,因此即使原始目录包含文件,新目录也为空。

另外,如果目标文件存在,则复制将失败,除非指定了REPLACE_EXISTING选项。

验证是否正确复制了文件。 随意修改代码并以自己喜欢的方式使用它。

祝您学习愉快!