在日常编码中所有被打开的资源,如IO流,数据库链接,Socket链接等,是需要手动关闭的,否则随着程序不断的运行,造成资源不断的浪费。所以关闭的动作一般写在finally块中,然后我们同时打开多个资源:
下面简单建立读写管道,必须要程序结束后随之关闭 ↓ 关闭代码比业务代码还要多!
FileInputStream fi = null;
FileOutputStream fo = null;
try {
fi = new FileInputStream(path);
fo = new FileOutputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fi.close();//手动关闭输入
fo.close();//手动关闭输出
} catch (IOException e) {
e.printStackTrace();
}//catch语块叠加,过程繁琐
}
使用try-with-resource ↓
try (FileInputStream fi = new FileInputStream(path);
FileOutputStream fo = new FileOutputStream(Path)) //try后面接括号,
//里面写建立的管道,程序运行结束时会自动关闭
{
int length = 0;
byte[] bytes = new byte[1024];
while ((length = fi.read(bytes)) != -1) {
fo.write(bytes, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
总结:
try-with-resource 是一个语法糖,它最终在还是被编译成了try-catch-finally,在finally里面关闭了我们的管道。
try-with-resource 只能在哪些需要关闭的管道操作或连接操作的时候使用,而不是任意的try-catch-finally都可以被替换。能够使用try-with-resource的管道必须实现一个AutoCloaseable的接口,然后重写这个接口的close方法。



