try-with-resource可以帮我们管理资源如关闭IO流,Socket。在try-catch语句块中不用我们手写冗长的finally代码。
1.写在try()中的外部资源句柄必须实现了AutoCloseable接口。
在try()里的语句不能是任意一个赋值语句,new出来或者其他方式初始化的对象必须实现AutoCloseable接口,
我们经常需要try-catch-finally的IO,Socket这块的类都已经实现了AutoCloseable接口。如字节流父类InputStream,OutputStream
我们在操作它子类时候就可以使用try-with-resource
2.try()中可以定义多个赋值语句,多个语句之间用分号分隔,最后一个语句后面不要带分号,如下例子。
//jdk7的try-with-resource,不用自己写finally关闭资源
try (FileInputStream fs = new FileInputStream(new File(""));
FileOutputStream fo = new FileOutputStream(new File(""))) {
//do somthing.....
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//传统方式
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(""));
//do somthing.....
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}