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

标签 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);
    }
}

最佳答案

目前代码还没有准备好处理异常——你缺少 finally block 来关闭打开的流。当然,您是对的 - 使用 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 - Sonar : How to use try-with-resources to close FileOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248572/

相关文章:

Java - 未单独指定实例化的类范围泛型类型

sql - 可以在 Sonar 中分析 SQL 查询吗?

Sonarqube 扫描仪报告上传错误 500

GoSonar : how to generate go test -json > report. json

java - Socket OutputStream 上的 PrintWriter 导致数据损坏/丢失

java - 读取上传文件的内容时,字符看起来像 "?"

java - Springsource Tool Suite 找不到站点

Java 和 JSTL/EL : How can I compare two integers stored as attributes?

java - 当尝试删除同一事务中的锁定实体时,EntityManager 抛出 OptimisticLockException

Apache 配置单元错误 Merging of credentials not supported in this version of hadoop