Sonar: How to use try-with-resources to close FileOutputStream

后端 未结 1 1878
情书的邮戳
情书的邮戳 2021-01-19 05:59

Sonar is giving an error that this FileOutputStream should be closed. I need to modify the following code to use try-with-resources. How do I do th

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 06:35

    Currently code is not ready to handle exceptions - you're missing finally block to close open streams. And, sure, you're right - using try-with-resources solves this problem:

    public void archivingTheFile(String zipFile) {
        byte[] buffer = new byte[1024];
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            for(String file : this.fileList) {
                try (FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file)) {
                    ZipEntry ze = new ZipEntry(file);
                    zos.putNextEntry(ze);
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
            }
        } catch(IOException ex) {
            LOGGER.error("Exception occurred while zipping file",ex);
        }
    }
    

    0 讨论(0)
提交回复
热议问题