一个Java复制目录的方法(递归)

 1     /**
 2      * 将目标目录复制为指定目录(也可以用于复制文件)
 3      * @param src 源路径
 4      * @param dest 目标路径
 5      * @throws IOException
 6      */
 7     public static void copyDir(File src, File dest) throws IOException {
 8         if(!src.exists()) {        // 检查源路径是否存在
 9             System.out.println("源目录不存在!");
10         } else if(src.isFile()) {    // 如果源路径是一个文件
11             if(dest.isDirectory()) {
12                 // 不能将文件复制为一个目录
13                 System.out.println("目标路径不是一个文件!");
14             }else {
15                 // 复制文件
16                 FileInputStream fis = new FileInputStream(src);
17                 FileOutputStream fos = new FileOutputStream(dest);
18                 byte[] arr = new byte[1024 * 8];
19                 int len;
20                 while((len = fis.read(arr)) != -1) {
21                     fos.write(arr, 0, len);
22                 }
23                 fis.close();
24                 fos.close();
25             }
26         } else {    // 如果源路径是一个目录
27             if(dest.isFile()) {
28                 // 不能将目录复制为一个文件
29                 System.out.println("目标路径不是一个目录!");
30             } else {
31                 // 先检查目标是否存在, 不存在则创建
32                 if(!dest.exists()) {
33                     dest.mkdirs();
34                 }
35                 // 如果目标路径是一个目录, 递归调用本方法进行复制
36                 // 获取源目录的子文件/目录
37                 String[] subFiles = src.list();
38                 // 遍历源目录进行复制
39                 for (String subFile : subFiles) {
40                     copyDir(new File(src, subFile), new File(dest, subFile));
41                 }
42             }
43         }
44     }
45 
46 /**
47      * 测试代码
48      * @param args
49      * @throws IOException
50      */
51     public static void main(String[] args) throws IOException {
52         Scanner sc = new Scanner(System.in);
53         System.out.println("请输入源路径:");
54         String src = sc.nextLine();
55         System.out.println("请输入目标路径:");
56         String dest = sc.nextLine();
57         copyDir(new File(src), new File(dest));
58     }
原文地址:https://www.cnblogs.com/zhenyu-go/p/5554985.html