声纳:如何使用try-with-resources关闭FileOutputStream

声纳给出了一个错误,该FileOutputStream应该关闭.我需要修改以下代码以使用try-with-resources.我该怎么做呢?

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){
            ZipEntry ze= new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        zos.close();
    }catch(IOException ex){
        LOGGER.error("Exception occurred while zipping file",ex);
    }
}

解决方法:

当前,代码尚不准备处理异常-您丢失了finally块来关闭打开的流.而且,当然,您是对的-使用try-with-resources解决了这个问题:

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);
    }
}
上一篇:java-Jacoco eclipse插件和SonarQube中的代码覆盖率百分比值不同


下一篇:SonarQube--linux安装与问题解决