关闭流

完成后,大多数流必须关闭,否则可能会引入内存泄漏或打开文件。即使抛出异常,关闭流也很重要。

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...
    }
}

请注意,关闭包装器流也将关闭其基础流。这意味着你无法包装流,关闭包装器,然后继续使用原始流。