1 //从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
2 @Test
3 public void t6(){
4 //1) 接受两个文件夹路径
5 //1.创建一个 字符缓冲流
6
7 BufferedReader br = null;
8 try {
9 br = new BufferedReader(new InputStreamReader(System.in));
10 System.out.println("请输入第一个文件夹路径");
11 //2.读取2行字符串
12 String str1 = br.readLine();
13 System.out.println("请输入第二个文件夹路径");
14 String str2 = br.readLine();
15 File file1 = new File(str1);
16 File file2 = new File(str2);
17 file2.mkdir();
18 File[] listFiles = file1.listFiles();
19 for(int i=0;i<listFiles.length;i++){
20 if(listFiles[i].isFile()){
21 File target = new File(file2, listFiles[i].getName());
22 copyFile(listFiles[i], target);
23 }
24 if(listFiles[i].isDirectory()){
25 //文件夹下面还是个文件夹,这个时候去拿到文件夹的路径
26 String source1 = str1+File.separator+listFiles[i].getName();
27 String target1 = str2+File.separator+listFiles[i].getName();
28 copyDir(source1,target1);
29 }
30 }
31
40 } catch (FileNotFoundException e) {
41 e.printStackTrace();
42 } catch (IOException e) {
43 e.printStackTrace();
44 }finally{
45 try {
46 br.close();
47 } catch (IOException e) {
48 // TODO Auto-generated catch block
49 e.printStackTrace();
50 }
51 }
52 }
53 private void copyDir(String source1, String target1) throws IOException {
54 File source = new File(source1);
55 File target = new File(target1);
56 target.mkdirs();
57 File[] files = source.listFiles();
58 for(int a=0;a<files.length;a++){
59 if(files[a].isFile()){
60 File target2 = new File(target,files[a].getName());
61 copyFile(files[a], target2);
62 }
63 if(files[a].isDirectory()){
64 String source3 = source1 +File.separator + files[a].getName();
65 String target3 = target1 +File.separator + files[a].getName();
66 //递归,对还是文件夹的文件夹在调用copyDir的方法,上面的if条件是递归的出口
67 copyDir(source3,target3);
68 }
69 }
70 }
71 private void copyFile(File file, File target) throws IOException {
72 BufferedInputStream bis = new BufferedInputStream(
73 new FileInputStream(file));
74 BufferedOutputStream bos = new BufferedOutputStream(
75 new FileOutputStream(target));
76 byte[] buf = new byte[1024];
77 int len = 0;
78 while((len=bis.read(buf))!= -1){
79 bos.write(buf, 0,len);
80 }
81 bis.close();
82 bos.close();
83 }