使用try-with-resource语法避免手动关闭资源,减少资源关闭代码处理,同样达到资源关闭的目的
不使用try-with-resource语法:
try{
资源打开
业务逻辑
}catch(Exception e){
异常处理
}finally{
资源关闭
}
使用try-with-resource语法:
try(资源打开){
业务逻辑
}catch(Exception e){
异常处理
}
不使用try-with-resource语法打开多个资源案例:
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
bin = new BufferedInputStream(new FileInputStream(new File("test1.txt")));
bout = new BufferedOutputStream(new FileOutputStream(new File("test2.txt")));
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bin != null) {
try {
bin.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bout != null) {
try {
bout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
使用try-with-resource语法打开多个资源案例:
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test1.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("test2.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}