在java中监视gzip下载进度

knpiaxh1  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(282)

我在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, 0, count);
    downloaded += count;
    this.stateChanged();
}

...

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

谢谢你的帮助!

cnjp1d6j

cnjp1d6j1#

根据规范, GZIPInputStream 是的一个子类 InflaterInputStream . 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();

相关问题