目标:复制指定源位置的所有文件、文件夹到指定的目标位置
分析:
1.如果指定源位置是文件,则直接复制文件到目标位置。
2.如果指定源位置是文件夹,则首先在目标文件夹下创建与源位置同名文件夹。
3.遍历源位置文件夹下所有的文件,修改源位置为当前遍历项的文件位置,目标位置为刚刚上部创建的文件夹位置。
4.递归调用,回到1.
编程实现
1 package cn.hafiz.www;
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 public class CopyFolder {
11 public static void main(String[] args) throws IOException {
12 File srcFile = new File("G:\\hafiz");
13 File desFile = new File("E:\\");
14 copyFolder(srcFile, desFile);
15 }
16
17 private static void copyFolder(File srcFile, File desFile) throws IOException {
18 if(srcFile.isDirectory()) {
19 //是文件夹,首先在目标位置创建同名文件夹,然后遍历文件夹下的文件,进行递归调用copyFolder函数
20 File newFolder = new File(desFile, srcFile.getName());
21 newFolder.mkdir();
22 File[] fileArray = srcFile.listFiles();
23 for(File file : fileArray) {
24 copyFolder(file, newFolder);
25 }
26 }else{
27 //是文件,直接copy到目标文件夹
28 File newFile = new File(desFile, srcFile.getName());
29 copyFile(srcFile, newFile);
30 }
31 }
32
33 private static void copyFile(File srcFile, File newFile) throws IOException {
34 //复制文件到指定位置
35 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
36 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
37 byte[] b = new byte[1024];
38 Integer len = 0;
39 while((len = bis.read(b)) != -1) {
40 bos.write(b, 0, len);
41 }
42 bis.close();
43 bos.close();
44 }
45 }
至此,多级文件的复制工作就完成了~