使用 @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();
    }
}

 

Posted on 2025-02-21 11:32  荆楚尬聊娃  阅读(39)  评论(0)    收藏  举报