IO流的應用(一):實現檔案的複製
阿新 • • 發佈:2018-11-01
package com.bjpowernode.demo03;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
- 使用FileReader/FileWriter實現文字檔案的複製
- @author Administrator
*/
public class Test02 {
public static void main(String[] args) { String srcFile = "D:/course/JavaProjects/03-JavaSE/Day08/src/com/bjpowernode/demo03/Test01.java" ; String destFile = "d:/test01.java" ; copyFile( srcFile, destFile); } //一次複製一個字元陣列, 自動關閉流 private static void copyFile(String srcFile, String destFile) { try ( FileReader fr = new FileReader(srcFile); FileWriter fw = new FileWriter(destFile); ){ char [] contents = new char[20]; int len = fr.read(contents); while( len != -1 ){ fw.write(contents, 0 , len); len = fr.read(contents); } } catch (Exception e) { } } // 一次複製一個字元, 手動關閉流, 異常處理 private static void copyFile2(String srcFile, String destFile) { FileReader fr = null; FileWriter fW = null; try { fr = new FileReader(srcFile); fW = new FileWriter(destFile); int cc = fr.read(); while( cc != -1){ fW.write(cc); cc = fr.read(); } } catch (Exception e) { }finally { if ( fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (fW != null ) { try { fW.close(); } catch (IOException e) { e.printStackTrace(); } } } }
}