try-with-resources是Java7中加入的,大大简化的对资源的管理,而且使用try-with-resources的代码清晰易懂
1、传统ry-catch-finally的写法
在管理多资源的时候尤其恐怖,如下:
/**
* 手动关闭
*/
public static void test1() {
String filePath = "D:\\test1\\test1.txt";
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(filePath));
fileInputStream = new FileInputStream(new File(filePath));
// 写
fileOutputStream.write("ab1024".getBytes(Charset.defaultCharset()));
// 读取
int data = fileInputStream.read();
while (data != -1) {
System.out.print((char) data);
data = fileInputStream.read();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭写流
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭读流
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
2、try-with-resources写法:
/**
* 自动关闭 try-with-resource
*/
public static void test2() throws Exception {
String filePath = "D:\\test1\\test1.txt";
// java7中的try-with-resource,java9中有所改善
try (FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
FileInputStream fileInputStream = new FileInputStream(new File(filePath))) {
// 写
fileOutputStream.write("ab1024".getBytes(Charset.defaultCharset()));
// 读取
int data = fileInputStream.read();
while (data != -1) {
System.out.print((char) data);
data = fileInputStream.read();
}
// 模拟异常
// int a = 0 / 0;
}
}
可以看出,精简了不少。
Java9对其进行了简单的优化,使用起来更加便捷;
// Java9可以这样写
FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
try (fileOutputStream;fileInputStream) {
// .......
}
原理:当try中代码执行结束后(正常结束或者异常结束),都会调用try()括号中对象的close()方法来关闭资源。
可以自己使用main方法测试,模拟抛出异常,捕获异常后对未关闭流的文件进行重命名或者删除操作,未关闭的文件是不能操作的,操作成功说明关闭成功。
3、实践
package onlytest;
import static java.lang.System.out;
public class testAutoClose {
public static void main(String[] args) {
try (MyClose close = new MyClose()) {
close.println("liuqinhou");
throw new Throwable("exist error");
} catch (Exception e) {
out.println("exception exists");
e.printStackTrace();
} catch (Throwable throwable) {
out.println("throwable exists");
throwable.printStackTrace();
}
out.println("main thread end");
}
}
class MyClose implements AutoCloseable {
public void println(String str) {
out.println(str + " is working...");
}
@Override
public void close() throws Exception {
out.println("MyClose is closed now");
}
}
输出结果为:
liuqinhou is working...
MyClose is closed now //try中代码执行后会立马执行resource对象的close方法,如果发生了异常,再执行catch中的语句
throwable exists
main thread end
java.lang.Throwable: exist error
at onlytest.testAutoClose.main(testAutoClose.java:10)
Process finished with exit code 0