代碼示例:java
1 import java.io.*; 2 3 public class CopyTest { 4 public static void main(String[] args) { 5 6 File srcDir = new File("./A"); 7 File tarDir = new File("./B"); 8 9 // 調用copyDir()方法,複製指定目錄下的全部文件 10 copyDir(srcDir,tarDir); 11 } 12 13 public static void copyDir(File srcDir, File tarDir) { 14 15 if(!tarDir.exists()) { 16 // 若目標目錄不存在,則使用File類中的mkdir()建立目錄 17 tarDir.mkdir(); 18 } 19 20 // 使用File類中的listFiles(),獲取指定目錄下的全部文件 21 File[] files = srcDir.listFiles(); 22 23 for(File file : files) { 24 if (file.isFile()) { 25 // 如果文件,則調用拷貝方法 26 copyFile(new File (srcDir + "\\" + file.getName()), new File(tarDir + "\\" + file.getName())); 27 28 }else { 29 // 如果目錄,則使用遞歸 30 copyDir(new File (srcDir + "\\" + file.getName()), new File(tarDir + "\\" + file.getName())); 31 } 32 } 33 } 34 35 public static void copyFile (File srcFile, File tarFile) { 36 37 BufferedInputStream bis = null; 38 BufferedOutputStream bos = null; 39 40 try { 41 bis = new BufferedInputStream(new FileInputStream(srcFile)); 42 bos = new BufferedOutputStream(new FileOutputStream(tarFile)); 43 44 byte[] buffer = new byte[1024]; 45 int len = 0; // 用於儲存讀取到的字節的個數 46 while( (len = bis.read(buffer)) != -1 ){ 47 bos.write(buffer,0,len); 48 } 49 }catch (FileNotFoundException e){ 50 e.printStackTrace(); 51 }catch (IOException e) { 52 e.printStackTrace(); 53 }finally { 54 if (bos != null) { 55 try { 56 bos.close(); 57 } catch (IOException e) { 58 e.printStackTrace(); 59 } 60 } 61 if (bis != null) { 62 try { 63 bis.close(); 64 } catch (IOException e) { 65 e.printStackTrace(); 66 } 67 } 68 } 69 } 70 }