Try括号代码逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try (
InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target)
){
byte[] buf = new byte[8192];

int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}
  • try括号内的资源会在try语句结束后自动释放,前提是这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。
  • InputStream 和OutputStream 父类中一定实现了AutoCloseable接口
  • ThreadLocal 作为属性 放到一个实现java.lang.AutoCloseable 接口类里,实现自动清理