【问题标题】:should i close FileOutputStream which is wrapped by ZipOutputStream [duplicate]我应该关闭由 ZipOutputStream 包装的 FileOutputStream [重复]
【发布时间】:2020-07-14 07:46:39
【问题描述】:

我正在编写一个批处理,下面将在循环中被调用很多次。所以我想知道我是否正确关闭了资源

//这将被循环调用

    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(zipFile);
        zos = new ZipOutputStream(fos);
     ...
     ...
     closeQuietly(zos)
     } catch(Exception e) {log.error(e.getMessage(),e);}

void closeQuietly(ZipOutputStream zos) {
        try {
            zos.closeEntry();
            zos.flush();
            zos.close();
        }
        catch(Exception e) {log.error(e.getMessage(),e);}
    }

我是否正确关闭了资源。我还需要在closeQuietly() 中关闭FileOutputStream

【问题讨论】:

标签: java zip fileoutputstream


【解决方案1】:

如果您查看documentation,您会发现 .close() “关闭 ZIP 输出流以及被过滤的流。”

所以你应该没问题

【讨论】:

    【解决方案2】:

    也可以通过尝试资源来达到,例如

      try (
          fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(fos)
        ) {
        your code  
        
     }
    

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2018-07-24
      • 2011-08-07
      • 2012-03-01
      相关资源
      最近更新 更多