當我們要復制帶有子目錄的文件夾的時候,就必須使用遞歸,這樣才能把全部的文件夾都復制到位
思路和步驟: 對於文件夾的復制,分2種情況
(1)當我們對文件進行遍歷的時候,如果目標文件夾下的文件是個標准文件的話,我們就可以直接去做復制的動作,
(2)當目標文件中,是帶有文件夾的文件,那么這個時候就需要對文件夾進行遞歸,直到最后它是個標准文件后,我們在做復制動作
有了上述的2種情況后,那么這個需求,需要提供2種方法,1是對標准文件的復制,2是對帶有文件夾的文件進行復制的操作
第一種,是標准的字節復制動作,很容易實現.
對於第二種,帶有文件夾的文件進行復制的方法的時候,由於文件夾下面可能還是個文件夾,那個這個時候就需要使用到遞歸,對文件夾復制的時候,進行判斷,是標准文件的話,直接用字節流復制的動作對它復制,如果它還是帶着目錄的話,我們就使用遞歸自己調用自己的方法,知道最后是標准文件,這時候在出棧,去進行字節的復制
具體代碼如下:
package wjd.copy; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyFile { public static void main(String[] args) throws IOException { //需要被復制文件夾的位置 String url1 = "c:" + File.separator + "source"; //最后被復制的文件夾 String url2 = "d:" + File.separator + "copy"; //將這2個文件夾包裝成File對象 File file1 = new File(url1); File file2 = new File(url2); //創建目標文件夾 file2.mkdirs(); //對源文件夾進行遍歷 File[] files = file1.listFiles(); for (int a = 0; a < files.length; a++) { //是標准文件,我們就直接進行復制動作 if (files[a].isFile()) { //確認目標文件的需要被復制到的位置,它肯定是在目標文件夾下面 File target = new File(file2, files[a].getName()); copyFile(files[a], target); } if(files[a].isDirectory()){ //文件夾下面還是個文件夾,這個時候去拿到文件夾的路徑 String source1 = url1+File.separator+files[a].getName(); String target1 = url2+File.separator+files[a].getName(); copyDir(source1,target1); } } } private static void copyDir(String source1, String target1) throws IOException { File source = new File(source1); File target = new File(target1); target.mkdirs(); File[] files = source.listFiles(); for(int a=0;a<files.length;a++){ if(files[a].isFile()){ File target2 = new File(target,files[a].getName()); copyFile(files[a], target2); } if(files[a].isDirectory()){ String source3 = source1 +File.separator + files[a].getName(); String target3 = target1 +File.separator + files[a].getName(); //遞歸,對還是文件夾的文件夾在調用copyDir的方法,上面的if條件是遞歸的出口 copyDir(source3,target3); } } } private static void copyFile(File file, File target) throws IOException { BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(target)); byte[] buf = new byte[1024]; int len = 0; while((len=bis.read(buf))!= -1){ bos.write(buf, 0,len); } bis.close(); bos.close(); } }