首页 > 解决方案 > 声纳错误:使用 try-with-resources 或在“finally”子句中关闭此“ZipOutputStream”

问题描述

我使用 Java 在 Spring Boot 应用程序中实现了 zip 下载方法。我尝试了几种不同的解决方案,但仍然收到:使用 try-with-resources 或在 Sonar 的“finally”子句错误中关闭此“ZipOutputStream”

在这里你可以找到我在服务中的实现。如果你能指导我解决这个问题,我会很高兴!

@Override
public void downloadZipBySeasonId(int seasonId, HttpServletResponse response) throws IOException {
.
.
.
    if(!items.isEmpty()) {
        ZipOutputStream zipOut = null;
        try {
            zipOut = new ZipOutputStream(response.getOutputStream());  // Sonar points this line!
            for (int i = 1; i <= items.size(); i++) {
                LetterEntity letter = items.get(i - 1);
                ZipEntry zipEntry = new ZipEntry(letter.getLetterName());
                zipOut.putNextEntry(zipEntry);
                StreamUtils.copy(letter.getLetterContent(), zipOut);
                zipOut.closeEntry();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Could not zip succesfully!");
        }
        finally {
            if(zipOut != null) {
                zipOut.finish();
                zipOut.close();
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + zipFileName + "\"");
    } else {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}

标签: javaspringspring-bootsonarqubesonarqube-scan

解决方案


尝试使用 ressources 自动关闭资源(Streams、Buffereds 等资源)你不需要关闭 finally 块中的读取器或写入器,你不需要编写 finally 块,也可以避免编写 catch 块。

例子

 try (BufferedReader r = Files.newBufferedReader(path1);
  BufferedWriter w = Files.newBufferedWriter(path2))
 {
  //protected code
 }
 catch (Exception e) {
  // exeption handler
 } 

文档:https ://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


推荐阅读