關閉流

完成後,大多數流必須關閉,否則可能會引入記憶體洩漏或開啟檔案。即使丟擲異常,關閉流也很重要。

Version >= Java SE 7

try(FileWriter fw = new FileWriter("outfilename");
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //handle this however you 
}

請記住:嘗試資源保證,退出塊時資源已關閉,無論是通常的控制流還是異常。

Version <= Java SE 6

有時,嘗試使用資源不是一種選擇,或者你可能支援舊版本的 Java 6 或更早版本。在這種情況下,正確的處理是使用 finally 塊:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt");
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //handle this however you want
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //typically not much you can do here...
    }
}

請注意,關閉包裝器流也將關閉其基礎流。這意味著你無法包裝流,關閉包裝器,然後繼續使用原始流。