try(){}catch{} 新写法 try-with-resource
JDK1.7之前
InputStream is = null;
OutputStream os = null;
try {
//...
} catch (IOException e) {
//...
}finally{
try {
if(os!=null){
os.close();
}
if(is!=null){
is.close();
}
} catch (IOException e2) {
//...
}
}
JDK1.7之后
在JDK7优化后的try-with-resource语句,该语句确保了每个资源,在语句结束时关闭。所谓的资源是指在程序完成后,必须关闭的流对象。写在()里面的流对象对应的类都实现了自动关闭接口AutoCloseable
try(
InputStream is = new FileInputStream("...");
OutputStream os = new FileOutputStream("...");
){
//...
}catch (IOException e) {
//...
}