声纳错误:使用资源试用或在"finally"子句中关闭此"ZipOutputStream"



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

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

@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);
}
}

将try与资源应用于初始代码将如下所示。在这里,您不必在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);
}

尝试自动关闭资源(例如Streams, Buffereds..)你不需要关闭finally块中的reader或writer,你不需要写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块中关闭资源的痛苦,也为您编写了几行额外的代码。尝试使用资源自动关闭资源,使您的代码简洁,并在任何情况下都注意关闭资源。

语法:

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 with resources:

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

相关内容

  • 没有找到相关文章

最新更新