我用 Java 在 Spring Boot 應用程式中實作了一個 zip 下載方法。我嘗試了幾種不同的解決方案,但我仍然收到:使用 try-with-resources 或在來自聲納的“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);
}
}
uj5u.com熱心網友回復:
嘗試使用資源自動關閉資源(資源如 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
uj5u.com熱心網友回復:
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();
}
uj5u.com熱心網友回復:
將 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342759.html
