1、 @Cleanup注解
public void contextLoads() throws Exception {
@Cleanup
FileInputStream fileInputStream = new FileInputStream("in");
@Cleanup
FileOutputStream fileOutputStream = new FileOutputStream("out");
int r;
while ((r = fileInputStream.read()) != -1) {
fileOutputStream.write(r);
}
}
编译后的class文件
2、try with resource
try (InputStream swapStream = new InputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
//业务操作
}
} catch (Exception e) {
//异常处理
}
把需要关闭的流new在try后面,加个括号,多个流用“;”分隔