Java关闭流
示例
使用完大多数流后,必须将其关闭,否则可能会导致内存泄漏或使文件保持打开状态。即使抛出异常,关闭流也很重要。
try(FileWriter fw = new FileWriter("outfilename");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//更多代码
out.println("more text");
//更多代码
} catch (IOException e) {
//处理这个但是你
}请记住:try-with-resources保证退出块时资源已关闭,无论是在通常的控制流中还是由于异常而发生。
有时,不可以使用try-with-resources,或者您正在支持Java6或更早版本。在这种情况下,正确的处理方法是使用一个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) {
//处理这个但是你 want
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//通常您在这里不能做的很多...
}
}