1. 程式人生 > >IO練習 兩個文件夾進行copy(含子目錄)

IO練習 兩個文件夾進行copy(含子目錄)

nts pan tor 拷貝 style copy str1 子目錄 red

 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 }

IO練習 兩個文件夾進行copy(含子目錄)