1 package copyFolderDemo;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9
10 /*
11 *
12 * 需求:复制多级文件夹
13 * 数据源:
14 * 目的地:
15 *
16 * 分析
17 * A:封装数据源、
18 * B:封装目的地
19 * C:判断该File是文件还是文件夹
20 * a:是文件夹
21 * 就在目的地下创建该文件夹
22 * 获取该File对象的所有文件或者文件夹对象
23 * 遍历得到每一个File对象
24 * 回到C
25 * b:是文件
26 * 复制文件
27 *
28 * */
29 public class CopyFoldersDemo {
30
31 public static void main(String[] args) throws IOException {
32
33 File srcFile=new File("h:\\movie");
34 File destFile=new File("h:\\copy-movie");
35 copyFolder(srcFile,destFile);
36
37 }
38
39 private static void copyFolder(File srcFile, File destFile) throws IOException {
40
41 if(srcFile.isDirectory()){
42 File newFolder=new File(destFile,srcFile.getName());
43 newFolder.mkdirs();
44 File[] fileArray=srcFile.listFiles();
45
46 for(File file:fileArray){
47 copyFolder(file, newFolder);
48 }
49
50 }else{
51 File newFile=new File(destFile,srcFile.getName());
52 copyFile(srcFile,newFile);
53 }
54
55 }
56
57 private static void copyFile(File srcFile, File newFile) throws IOException{
58 // TODO Auto-generated method stub
59 BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
60 BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(newFile));
61
62 byte[] bys=new byte[1024];
63 int len=0;
64 while((len=bis.read(bys))!=-1){
65 bos.write(bys,0,len);
66 }
67 bos.close();
68 bis.close();
69
70 }
71
72 }