2011-03-20 95 views

回答

17

Apache Commons IO可以爲你做詭計。看看FileUtils

+0

鏈接已關閉。請更新 – 4ndro1d 2013-04-25 09:54:11

+1

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29 – Raghunandan 2013-05-14 05:21:29

44

選擇你喜歡的:從Apache的百科全書IO

  • 文件實用程序(最簡單,最安全的方式

例如使用文件實用程序:

File srcDir = new File("C:/Demo/source"); 
File destDir = new File("C:/Demo/target"); 
FileUtils.copyDirectory(srcDir, destDir); 

實施例在Java 7 AutoCloseable特徵:

public void copy(File sourceLocation, File targetLocation) throws IOException { 
    if (sourceLocation.isDirectory()) { 
     copyDirectory(sourceLocation, targetLocation); 
    } else { 
     copyFile(sourceLocation, targetLocation); 
    } 
} 

private void copyDirectory(File source, File target) throws IOException { 
    if (!target.exists()) { 
     target.mkdir(); 
    } 

    for (String f : source.list()) { 
     copy(new File(source, f), new File(target, f)); 
    } 
} 

private void copyFile(File source, File target) throws IOException {   
    try (
      InputStream in = new FileInputStream(source); 
      OutputStream out = new FileOutputStream(target) 
    ) { 
     byte[] buf = new byte[1024]; 
     int length; 
     while ((length = in.read(buf)) > 0) { 
      out.write(buf, 0, length); 
     } 
    } 
} 
+0

這是行得通的,但如果發生異常,您將不會關閉流:您應該添加try catch finally塊。 – 2014-09-14 18:41:15

+0

@Tim,的確如此。固定 – smas 2014-09-14 20:33:50

2

看的java.io.File爲一組函數。

您將遍歷現有結構和mkdir,保存等來實現深層複製。

相關問題