java關流的正確姿勢

月光邊境發表於2018-01-16

####錯誤示例1

public void CopyFile() {
        FileReader fr = null;
        FileWriter fw = null;

        try {

            fr = new FileReader("c:\\xy1.txt"); // ①
            fw = new FileWriter("c:\\xy2.txt"); // ②

            char[] charBuffer = new char[1024];
            int len = 0;
            while ((len = fr.read(charBuffer)) != -1) {
                fw.write(charBuffer, 0, len);
            }
            System.out.println("檔案複製成功");

        } catch (IOException e) {
            throw new RuntimeException("檔案拷貝操作失敗");
        } finally {
            try {
                fr.close(); // ③
                fw.close(); // ④
            } catch (IOException e) {
                throw new RuntimeException("關閉失敗");
            }
        }
    }```

若①中程式碼出錯,fr根本就沒有初始化,執行③的時候就會報空指標異常。②④同樣是這個道理。

####錯誤示例2
複製程式碼

public void CopyFile() { FileReader fr = null; FileWriter fw = null;

    try {

        fr = new FileReader("c:\\xy1.txt"); // ①
        fw = new FileWriter("c:\\xy2.txt"); // ②

        char[] charBuffer = new char[1024];
        int len = 0;
        while ((len = fr.read(charBuffer)) != -1) {
            fw.write(charBuffer, 0, len);
        }
        System.out.println("檔案複製成功");
    } catch (IOException e) {
        throw new RuntimeException("檔案拷貝操作失敗");
    } finally {
        try {
            if (null != fr) {
                fr.close(); // ③
            }
            if (null != fw) {
                fw.close(); // ④
            }

        } catch (IOException e) {
            throw new RuntimeException("關閉失敗"); // ⑤
        }
    }
}```
複製程式碼

加上是否為空的判斷可以避免空指標異常。但是如果③執行出錯,程式會直接進入⑤而④根本沒有得到執行,導致無法關閉。

####正確關流姿勢:

 public void CopyFile() {
        FileReader fr = null;
        FileWriter fw = null;

        try {
            fr = new FileReader("c:\\xy1.txt");
            fw = new FileWriter("c:\\xy2.txt");
           
            char[] charBuffer = new char[1024];
            int len = 0;
            while ((len = fr.read(charBuffer)) != -1) {
                fw.write(charBuffer, 0, len);
            }
            System.out.println("檔案複製成功");
        } catch (IOException e) {
            throw new RuntimeException("檔案拷貝操作失敗");
        } finally {
            try {
                if (null != fr) {
                    fr.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("關閉失敗");
            }

            try {
                if (null != fw) {
                    fw.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("關閉失敗");
            }
        }
    }
複製程式碼

相關文章