坚持英文原版阅读.
尽可能使用try-with-resources,而不是try-finally。
这是JAVA7新增特性。
Why prefer try-with-resources to try-finally?
首先看看一下代码:
static void copy(String src, String dst) {
InputStream in = null;
try {
in = new FileInputStream(src);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读文件只需要一行代码,但是try-finally用了10行,出现了大量模板代码。try-with-resources对这种模板代码进行了优化:
static void copy(String src, String dst) {
try (
InputStream in = new FileInputStream(src);
){
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
减少了模板代码,而且不需要显示关闭流