Sonar Error: Use try-with-resources or close this "ZipOutputStream" in a "finally" clause

Sonar Error: Use try-with-resources or close this "ZipOutputStream" in a "finally" clause

我使用 Java 在 Spring 引导应用程序中实现了 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);
    }
}

尝试使用资源自动关闭资源(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

将 try with resources 应用于初始代码如下。在这里,您不必在 finally 块中关闭流。当退出 try catch 块时关闭。存在声纳问题是因为空检查。

 if(!items.isEmpty()) {
        
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());){
            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!");
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + zipFileName + "\"");
    } else {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }

Try with resources 是一个非常漂亮的概念,它消除了在 finally 块中关闭资源的痛苦,这也是您编写的几行额外代码。 Try with resources 自动关闭资源,让你的代码简洁,在任何情况下都能照顾到关闭资源。

语法:

    Scanner scanner = null;
try {
    scanner = new Scanner(new File("scan.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}

尝试使用资源:

    try (Scanner scanner = new Scanner(new File("scan.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}