Sonar常见问题及修改建议(202001):https://blog.csdn.net/libusi001/article/details/103717457
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
一、报错信息
Use try-with-resources or close this "BufferedOutputStream" in a "finally" clause.
使用try-with-resources或在“ finally”子句中关闭此“ BufferedOutputStream”。
二、源代码
try {
BufferedOutputStream out = out = new BufferedOutputStream(
new FileOutputStream(new File(legalizeExamTemplatePath,newFileName)));
out.write(file.getBytes());
out.flush();
out.close();
} catch (IOException e) {
return Result.error("上传失败!");
}
如果出现异常会跳转到catch,那么out.close()就不会执行。
所以需要在“ finally”子句中关闭此“ BufferedOutputStream”。
BufferedOutputStream需要写在try外面才行,而且必须初始化,初始化为null。
这样又会报空指针异常,所以需要判空,优化代码如下;
三、优化后代码
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(
new FileOutputStream(new File(legalizeExamTemplatePath, newFileName)));
out.write(file.getBytes());
out.flush();
log.info("上传成功!");
return Result.success("上传成功!", null);
} catch (IOException e) {
return Result.error("上传失败!");
} finally {
CloseIoUtils.closeAll(out);
}
Java IO流关闭工具类详解:https://blog.csdn.net/libusi001/article/details/100741637
有用请点赞,养成良好习惯!
鼓励、疑问、交流请留言!