首页 > 技术文章 > 复制文件夹里面的文件(包括文件夹及里面包含的文件)

EvanTheGreat 2021-02-23 22:09 原文

这里,有了文件夹,难度就升高了,但是其实也没难到哪里去,我们的思路就是利用递归来解决这个问题。

 1 package com.hw.file0223;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.nio.file.Files;
 6 
 7 import org.junit.Test;
 8 
 9 
10 public class PracticeTest03 {
11     
12     @Test
13     public void testTest03(){
14         test03(new File("F://骚操作"),new File("F://骚操作附件"));
15     }
16     
17     public void test03(File sourceFolder,File targetFolder){
18         
19         if(!targetFolder.exists()){
20             targetFolder.mkdirs();
21         }
22         
23         File[] files = sourceFolder.listFiles();  
24         
25         for(File file : files)
26         {
27             if(file.isDirectory()){
28                 File newFiles = new File(targetFolder,file.getName());
29                 test03(file,newFiles);
30             }else{
31                 File newFiles = new File(targetFolder,file.getName());
32                 try {
33                     Files.copy(file.toPath(), newFiles.toPath());
34                 } catch (IOException e) {
35                     // TODO Auto-generated catch block
36                     e.printStackTrace();
37                 }
38             }
39             
40         }
41     }
42 }

 

 

推荐阅读