如何使用Optional
或Java 8+功能(lambdas?)关闭Reader
、InputStream
和其他内容。
多年来,我一直在使用以下有效的代码,但是是否存在更好的方法,可以使用 Java 8+ 编写更少的代码行?
编辑:在我的情况下,我不能使用 try-with-resources。
private Reader reader;
// Time to close the reader
if (this.reader != null) {
try {
this.reader.close();
}
catch(IOException e) {
LOGGER.warn(e.getMessage(), e);
}
this.reader = null;
}
问候,
最佳答案
尝试资源
try(Reader reader = new StringReader(str)){
//code
}catch(Exception e) {
e.printStackTrace();
}
您不需要关闭阅读器
关于java - 我可以使用 Java 8+ 比 Java 7 及更低版本中更少的代码行来关闭 InputStream、Reader、Writer...吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975824/