加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

监控GZip下载Java的进展

发布时间:2020-12-14 19:20:52 所属栏目:Java 来源:网络整理
导读:我在我的Java应用程序中下载了一些文件并实现了下载监视器对话框.但最近我使用gzip压缩了所有文件,现在下载监视器有点破碎了. 我将文件作为GZIPInputStream打开,并在每次下载KB后更新下载状态.如果文件大小为1MB,则进度可达到4MB是未压缩的大小.我想监视压缩

我在我的Java应用程序中下载了一些文件并实现了下载监视器对话框.但最近我使用gzip压缩了所有文件,现在下载监视器有点破碎了.

我将文件作为GZIPInputStream打开,并在每次下载KB后更新下载状态.如果文件大小为1MB,则进度可达到4MB是未压缩的大小.我想监视压缩的下载进度.这可能吗?

编辑:澄清:我正在读取GZipInputStream中的字节,这些字节是未压缩的字节.所以这并没有给我正确的文件大小.

这是我的代码:

URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
...
File file = new File("bibles/" + name + ".xml");
if(!file.exists())
    file.createNewFile();
out = new FileOutputStream(file);
in = new BufferedInputStream(new GZIPInputStream(con.getInputStream()));

byte[] buffer = new byte[1024];
int count;
while((count = in.read(buffer)) != -1) {
    out.write(buffer,count);
    downloaded += count;
    this.stateChanged();
}

...

private void stateChanged() {
    this.setChanged();
    this.notifyObservers();
}

谢谢你的帮助!

最佳答案
根据规范,GZIPInputStreamInflaterInputStream的子类.InflaterInputStream具有protected Inflater inf字段,其是用于解压缩工作的Inflater. Inflater.getBytesRead应该对您的目的特别有用.

不幸的是,GZIPInputStream不会暴露inf,所以可能你必须创建自己的子类并暴露Inflater,例如

public final class ExposedGZIPInputStream extends GZIPInputStream {

  public ExposedGZIPInputStream(final InputStream stream) {
    super(stream);
  }

  public ExposedGZIPInputStream(final InputStream stream,final int n) {
    super(stream,n);
  }

  public Inflater inflater() {
    return super.inf;
  }
}
...
final ExposedGZIPInputStream gzip = new ExposedGZIPInputStream(...);
...
final Inflater inflater = gzip.inflater();
final long read = inflater.getBytesRead();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读