声纳引发了fileStream未在下面的代码中关闭的问题。但是,它是在lambda表达式中。如何解决声纳问题:当流真的关闭,但在lambda中时,流并未关闭
try {
final InputStream fileStream = new FileInputStream(copy);
return (OutputStream outputStream) -> {
int n;
byte[] buffer = new byte[1024];
while ((n = fileStream.read(buffer)) > -1) {
outputStream.write(buffer, 0, n);
}
fileStream.close();
};
} catch (IOException exception) {
...
}
当我改变它,使用try-与资源模式,然后我得到异常:产生java.io.IOException:流闭阅读FILESTREAM线:
try (final InputStream fileStream = new FileInputStream(copy)) {
return (OutputStream outputStream) -> {
int n;
byte[] buffer = new byte[1024];
while ((n = fileStream.read(buffer)) > -1) {
outputStream.write(buffer, 0, n);
}
};
} catch (IOException exception) {
...
}
因此第二个解决方案解决了sonar检测到的bug,但是它只是在lambda代码被调用之前关闭fileStream时不起作用。
你会建议如何解决它?
如果发生异常,该方法可能会在outputStream.close()调用完成之前跳出。将close命令添加到catch块或使用try-with-resource来解决此问题。 – Korashen