首頁 > JAVA > Java Copy 檔案及資料夾的方法

Java Copy 檔案及資料夾的方法

2008年8月20日 發表評論 閱讀評論

Java對檔案的處理,已經提供非常完整的API
不過像複製檔案的功能,還是要再手動多寫幾行code才行
以下就介紹copy 檔案的方式,順便說一下如何copy 資料夾

1.這是最基本的方式,利用read()方式進行複製動作

public void copyFile(String srFile, String dtFile){
  try{
     File f1 = new File(srFile);
     File f2 = new File(dtFile);
     InputStream in = new FileInputStream(f1);
     OutputStream out = new FileOutputStream(f2);
     byte[] buf = new byte[1024];
     int len;
     while ((len = in.read(buf)) > 0){
       out.write(buf, 0, len);
     }
     in.close();
     out.close();
  }
  catch(FileNotFoundException ex){
     ex.printStackTrace(); 
  }
  catch(IOException e){
     ex.printStackTrace();   
  }
}

2.在JDK 1.4時,多了一些對IO處理的API放在java.nio這個package,叫做NIO (NEW I/O),先前JAVA提供的IO都會blocking IO,因此導致很多Thread在進行IO處理時就會造成整體效能變差,NIO它的最大優點,是可以在同一條 thread 讀寫多個channel而不會被單一的IO blocking限制效率並且也減少多了透過byte[]方式的動作。所以我們也提供NIO複製的方式

public  void copyFile(String srFile, String dtFile){
  try{
       FileChannel srcChannel = new FileInputStream(srFile).getChannel();
       FileChannel dstChannel = new FileOutputStream(dtFile).getChannel();
       dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
       srcChannel.close();
       dstChannel.close();
  } catch (IOException e) {
      e.printStackTrace();   
  }
}

3.複製資料夾,當然能複製檔案外,也可以寫個小method來進行資料夾的複製,有點像xcopy的方式,這裡要注意,以下的程式碼copyFile 是傳入File而非上述sample code的String,請自行再調整一下

public void copyDirectory(File source, File target) {  
       File[] file = source.listFiles();
       for (int i = 0; i < file.length; i++) {  
           if (file[i].isFile()) { 
               File sourceDemo = new File(source.getAbsolutePath() + “/” 
                       + file[i].getName());  
               File destDemo = new File(target.getAbsolutePath() + “/” 
                       + file[i].getName());  
               this.copyFile(sourceDemo, destDemo);  
           }  
           if (file[i].isDirectory()) {
               File sourceDemo = new File(source.getAbsolutePath() + “/” 
                       + file[i].getName());  
               File destDemo = new File(target.getAbsolutePath() + “/” 
                       + file[i].getName());  
               destDemo.mkdir();
               this.copyDirectory(sourceDemo, destDemo);  
           }  
       }
  }

參考資料:

Be Sociable, Share!
Categories: JAVA Tags: , ,
  1. 小C
    2009年8月19日16:13 | #1

    你的方法二的public宣告寫錯了 ><

    [回應]

    Hero 回應:

    哈~~筆誤 已修正 感恩喔!!

    [回應]

  1. 目前尚無任何 trackbacks 和 pingbacks。

*