声纳:如何使用try-with-resources关闭FileOutputStream [英] Sonar: How to use try-with-resources to close FileOutputStream

查看:212
本文介绍了声纳:如何使用try-with-resources关闭FileOutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sonar发出错误,应该关闭此 FileOutputStream 。我需要修改以下代码才能使用 try-with-resources 。我该怎么做?

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 this?

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


推荐答案

目前代码还没有准备好处理异常 - 你最终错过了关闭开放流的块。当然,你是对的 - 使用try-with-resources解决了这个问题:

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

这篇关于声纳:如何使用try-with-resources关闭FileOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆