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) {
}
}