【发布时间】:2017-10-06 10:53:16
【问题描述】:
Sonar 在下面的代码中提出了 fileStream 未关闭的问题。然而它是,但在 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-with-resource 模式时,我得到异常:java.io.IOException: Stream Closed in the line of reading 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) {
//...
}
因此,第二个解决方案解决了声纳检测到的错误,但是它不起作用,因为在调用 lambda 代码之前关闭了 fileStream。
您会建议如何解决它?
【问题讨论】:
-
如果发生异常,该方法可能会在 outputStream.close() 调用完成之前跳出。将关闭命令添加到 catch 块或使用 try-with-resource 来解决此问题。
标签: java lambda stream sonarqube