使用 @Cleanup 可以很便捷的关闭流
@Cleanup InputStream fileInputStream = file.getInputStream();
xxx
xxx
xxx
相当于
InputStream fileInputStream = file.getInputStream();
try {
xxx
xxx
xxx
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
@Cleanup 支持指定方法名
@Target(ElementType.LOCAL_VARIABLE)
@Retention(RetentionPolicy.SOURCE)
public @interface Cleanup {
String value() default "close";
}
比如清除临时文件
@Cleanup("delete") File tempFile = new File( "c://temp/temp.txt'" );
xxx
xxx
xxx
转化后就是
File tempFile = new File( "c://temp/temp.txt'" );
try {
xxx
xxx
xxx
} finally {
if (tempFile != null) {
tempFile.delete();
}
}
浙公网安备 33010602011771号