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

时间:2016-12-20 18:00:38

标签: java sonarqube java-io try-with-resources

Sonar发出一个错误,即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);
    }
}

1 个答案:

答案 0 :(得分:4)

目前代码尚未准备好处理异常 - 您最终会遗漏阻止关闭开放流。而且,当然,你是对的 - 使用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);
    }
}