gpt4 book ai didi

java - 声纳显示不良实践方法可能无法在异常时关闭流

转载 作者:行者123 更新时间:2023-12-01 15:05:04 25 4
gpt4 key购买 nike

Possible Duplicate:
Sonar violation: “Method may fail to close stream on exception”

我有一个使用 DataInputStream 的方法,代码如下:

DataInputStream in = null;
ServletOutputStream outStream = null;
FileInputStream fileIn = null;
URL searchDirectory;
try {
searchDirectory = (java.net.URL) ctx.lookup("file/testHarnessDirectory");

File file = new File(searchDirectory.getPath(), filename);
int length = 0;
outStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());

response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\"");
byte[] byteBuffer = new byte[4096];
fileIn = new FileInputStream(file);
in = new DataInputStream(fileIn);

while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
outStream.write(byteBuffer, 0, length);
}
outStream.close();
fileIn.close();
in.close();
}
catch (NamingException e) {
LOG.error("Exception", e);
throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not download File", e);
}
catch (IOException e) {
LOG.error("Exception", e);
throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not submit File", e);
}
finally {
try {
if (fileIn != null) {
fileIn.close();
}
if (in != null) {
in.close();
}
if (outStream != null) {
outStream.close();
}
}
catch (IOException e) {
LOG.error("Exception", e);
throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not submit File", e);}}

但是声纳给了我:不好的做法 - 方法可能无法在异常时关闭流。我查过这篇文章:Sonar violation: "Method may fail to close stream on exception" ,但对我来说似乎不完整。我可能是错的。谁能告诉我,关闭流的简单方法是什么?

最佳答案

检查此部分:

 try {
if (fileIn != null) {
fileIn.close();
}
if (in != null) {
in.close();
}
if (outStream != null) {
outStream.close();
}
}

并想一想,如果 fileIn.close() 失败会发生什么。其他两个流可能保持开放。请将它们放在单独的 try-catch block 中。例如

 try {
if (fileIn != null) {
fileIn.close();
}
}catch (IOException e) {
LOG.error("Exception: Could not close file stream", e);
//throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close file stream", e);
}
try {
if (in != null) {
in.close();
}
}catch (IOException e) {
LOG.error("Exception: Could not close in stream"", e);
//throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close in stream", e);
}
try {
if (outStream != null) {
outStream.close();
}
}
}catch (IOException e) {
LOG.error("Exception: Could not close out stream", e);
//throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close out stream", e);
}

关于java - 声纳显示不良实践方法可能无法在异常时关闭流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com