Use try-with-resources or close this “BufferedOutputStream“ in a “finally“ clause.
Sonar常见问题及修改建议(202001):https://blog.csdn.net/libusi001/article/details/103717457~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~一、报错信息Use try-with-resources or close this "BufferedOutputStream"...
·
Sonar常见问题及修改建议2021(持续更新!!) 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); }
try(BufferedOutputStream 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("上传失败!"); }
Java IO流关闭工具类详解:https://blog.csdn.net/libusi001/article/details/100741637
有用请点赞,养成良好习惯!
鼓励、疑问、交流请留言!
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献15条内容
所有评论(0)