Java 所有流都得在用完后关闭,避免造成资源浪费及攻击。
最老的try - catch - finally 很不优雅
private void trt_catch_finally(){
String filepath = "a.xml";
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(filepath);
String str;
// 按行读取字符串
while ((str = bf.readLine()) != null)
System.out.println(str);
} catch (Exception e) {
}
finally {
if(null != bf){
try {
bf.close();
} catch (IOException e) {
}
}
}
}
后来有段时间接触了org.apache.commons.io.IOUtils,会简洁一点点。点进源码看是他帮我们封装好了
private void IOUtils(){
String filepath = "a.xml";
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(filepath);
String str;
// 按行读取字符串
while ((str = bf.readLine()) != null)
System.out.println(str);
} catch (Exception e) {
}
finally {
IOUtils.closeQuietly(bf);
}
}
现在JDK7后,有了最新的try-with-resource,可以直接省略了关流,由JVM去处理
private void try_with_resource(){
String filepath = "a.xml";
try (BufferedReader bf = new BufferedReader(new FileReader(filepath))) {
String str;
// 按行读取字符串
while ((str = bf.readLine()) != null)
System.out.println(str);
} catch (Exception e) {
}
}

本文总结了Java中处理流的关闭方法,从传统的try-catch-finally到Apache Commons IOUtils的使用,再到JDK7引入的try-with-resource语句,探讨了如何优雅且有效地管理流的关闭,确保资源的正确释放。
326

被折叠的 条评论
为什么被折叠?



