Archive

2008年8月20日 的Archive

Java Copy 檔案及資料夾的方法

2008年8月20日 2 則評論

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);  
           }  
       }
  }

參考資料:

Categories: JAVA Tags: , ,

堆疊(Stack) 和佇列(Queue) 基本說明

2008年8月20日 尚無評論

這兩個名詞常聽到,不過稍不注意,很容易搞混其意思,所以在此列出之間的特性及重點

堆疊(Stack)

  • 資料的插入和刪除只發生在堆疊的頂端(Top)
  • 使得資料進出堆疊時產生「後進先出」(LIFO)的特性
  • 使用範例
    • 歐式自助餐之餐盤堆放方式
    • 副程式的呼叫和返回
    • 堆積木
    • 蓋房子
    • 空間堆放求得最佳步驟
    • 數學四則運算

佇列(Queue)

    • 佇列也是一個有序串列
    • 資料的插入和刪除分別發生在佇列結構的兩端
    • 插入資料的一端叫做尾端(Rear),刪除資料的一端叫做前端(Front)
    • 資料進出佇列的次序形成「先進者先出」的特性 (FIFO)
    • 使用範例
Categories: 程式開發 Tags: , , ,