FileWriter
巢狀 例外處理,外層 try-catch 捕捉內層 拋出的例外
※讀取AAA.txt檔案,寫入CopyFile.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CopyFileTest { public static void main(String[] args) { FileReader fr = null; FileWriter fw = null; try { try { fr = new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt"); fw = new FileWriter("C:/Users/Administrator/Desktop/MyJava/CopyFile.txt"); int i; while ((i = fr.read()) != -1) { fw.write(i); //將檔案寫入 } } finally { //資源關閉 if (fr != null) { fr.close(); } if (fw != null) { fw.close(); } } } catch (IOException e) { //捕捉所有IOException(含子類別) System.out.println(e); } } } |
使用緩衝區
BufferedReader、BufferedWriter
所謂的緩衝區,指的是像陣列的概念,預先準備一塊空間來放資料,省去頻繁的硬體操作,提高執行效率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import java.io.*; public class CopyFileTest2 { public static void main(String[] args) { FileReader fr = null; FileWriter fw = null; BufferedReader br = null; BufferedWriter bw = null; try { try { fr = new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt"); fw = new FileWriter("C:/Users/Administrator/Desktop/MyJava/CopyFile.txt"); //將檔案導入緩衝區的資料流 br = new BufferedReader(fr); bw = new BufferedWriter(fw); String s; while ((s = br.readLine()) != null) {//讀取一行,當讀取不到資料回回傳null bw.write(s);//輸出字串 bw.newLine();//輸出換行 } } finally { if (bw != null) { bw.flush();//將緩衝區的資料寫入 bw.close(); } if (br != null) { br.close(); } } } catch (IOException e) { System.out.println(e); } } } |
用 Java 7 提供的自動關閉資源語法改寫
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.io.*; public class CopyFileTest3 { public static void main(String[] args) { //用 Java 7 提供的自動關閉資源語法改寫 try (BufferedReader br = new BufferedReader(new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("C:/Users/Administrator/Desktop/MyJava/CopyFile.txt"))) { String s; while ((s = br.readLine()) != null) {//讀取一行,當讀取不到資料回回傳null bw.write(s);//輸出字串 bw.newLine();//輸出換行 } bw.flush();//將緩衝區的資料寫入 } catch (IOException e) { System.out.println(e); } } } |
沒有留言:
張貼留言