javase复制文件夹

 1 package com.copyfile;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 
 9 import org.junit.Test;
10 
11 public class FileTraverse {
12 
13     public static void main(String[] args) {
14         // TODO Auto-generated method stub
15         String file = "E:\大数据资料\视频\01_十八掌教育_徐培成_大数据零基础教程\01-Java基础\Java基础第01天\02-Java简介-DOS命令.avi";
16         reverse(file);
17         copyDir("D:\arch", "e:\arch");
18     }
19 
20     /**
21      * 打印输出目录结构
22      * 
23      * @param file
24      */
25     public static void reverse(String file) {
26         File dir = new File(file);
27         if (dir.exists()) {
28             System.out.println(dir.getAbsolutePath());
29             if (dir.isDirectory()) {
30                 File[] files = dir.listFiles();
31                 if (files != null && files.length > 0) {
32                     for (File f : files) {
33                         reverse(f.getAbsolutePath());
34                     }
35                 }
36             }
37         }
38     }
39 
40     /**
41      * 复制文件夹
42      */
43     public static void copyDir(String file, String destDir) {
44         File f = new File(file);
45         if (f.exists()) {
46             // 如果是目录
47             if (f.isDirectory()) {
48                 // 创建新的目录
49                 File newFile = new File(destDir, f.getName());
50                 newFile.mkdir();
51                 File[] files = f.listFiles();
52                 if (files != null && files.length > 0) {
53                     for (File ff : files) {
54                         copyDir(ff.getAbsolutePath(), newFile.getAbsolutePath());
55                     }
56                 }
57             } else {
58                 copyFile(file, destDir);
59             }
60         }
61     }
62 
63     // 复制文件
64     private static void copyFile(String srcfile, String destDir) {
65         try {
66             File file = new File(srcfile);
67             File newFile = new File(destDir, file.getName());
68             FileInputStream fis = new FileInputStream(file);
69             FileOutputStream fos = new FileOutputStream(newFile);
70             byte[] buf = new byte[1024];
71             int len = 0;
72             while((len=fis.read(buf)) != -1) {
73                 fos.write(buf, 0, len);
74             }
75             fis.close();
76             fos.close();
77         } catch (Exception e) {
78             // TODO Auto-generated catch block
79             e.printStackTrace();
80         }
81     }
82 
83     @Test
84     public void test() {
85         copyFile("D:\arch", "e:\arch");
86     }
87 }
原文地址:https://www.cnblogs.com/yihaifutai/p/6752023.html