首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用GZIPOutputStream时当前文件大小

使用GZIPOutputStream时当前文件大小
EN

Stack Overflow用户
提问于 2014-07-30 10:54:17
回答 2查看 2K关注 0票数 2

我正在以异步方式使用GZIPOutputStream将压缩数据写入磁盘。

我想知道已经写入的数据的大小,这样我就可以在文件达到极限时关闭它。

代码语言:javascript
复制
ByteBuffer src;
//..
//data added to src here
//..
File theFile = new File("hello.gz");
FileOutputStream fos = new FileOutputStream(theFile);
GZIPOutputStream zs = new GZIPOutputStream(fos);
BufferedWriter zipwriter = new BufferedWriter(new OutputStreamWriter(zs, "UTF-8"));

(while_more_data)
{
   zipwriter.write(src.get());
   // check current file size here and close file if limit is reached
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-30 11:08:51

将您的FileOutputStream封装到另一个输出流中,它能够计算写入的字节数,比如第三方库雅加达公域IO提供的CountingOutputStream,或者番石榴中的CountingOutputStream

实现可以类似于:

代码语言:javascript
复制
ByteBuffer src;
//..
//data added to src here
//..
File theFile = new File("hello.gz");
try (FileOutputStream fos = new FileOutputStream(theFile);
     CountingOutputStream cos = new CountingOutputStream(fos);
     GZIPOutputStream zs = new GZIPOutputStream(cos);
     BufferedWriter zipwriter = new BufferedWriter(new OutputStreamWriter(zs, "UTF-8"))) {

    (while_more_data) {
        zipwriter.write(src.get());
        zipwriter.flush(); // make sure, data passes cos
        if (cos.getByteCount() >= limit) {
            // limit reached
        }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2017-09-08 05:21:22

如果您不想进入整个库,如番石榴公-IO,则只需扩展GZIPOutputStream并从关联的平移器获取数据,如下所示:

代码语言:javascript
复制
public class MyGZIPOutputStream extends GZIPOutputStream {

  public GZIPOutputStream(OutputStream out) throws IOException {
      super(out);
  }

  public long getBytesRead() {
      return def.getBytesRead();
  }

  public long getBytesWritten() {
      return def.getBytesWritten();
  }

  public void setLevel(int level) {
      def.setLevel(level);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25034996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档