简体   繁体   English

监控GZip下载Java的进展

[英]Monitor GZip Download Progress in Java

I download some files in my java app and implemented a download monitor dialog. 我在我的Java应用程序中下载了一些文件并实现了下载监视器对话框。 But recently I compressed all the files with gzip and now the download monitor is kind of broken. 但最近我使用gzip压缩了所有文件,现在下载监视器有点破碎了。

I open the file as a GZIPInputStream and update the download status after every kB downloaded. 我将文件作为GZIPInputStream打开,并在每次下载KB后更新下载状态。 If the file has a size of 1MB the progress goes up to eg 4MB which is the uncompressed size. 如果文件的大小为1MB,则进度上升到例如4MB,这是未压缩的大小。 I want to monitor the compressed download progress. 我想监视压缩的下载进度。 Is this possible? 这可能吗?

EDIT: To clarify: I'm reading the bytes from the GZipInputStream which are the uncompressed bytes. 编辑:澄清:我正在读取GZipInputStream中的字节,这些字节是未压缩的字节。 So that does not give me the right filesize at the end. 所以这并没有给我正确的文件大小。

Here is my code: 这是我的代码:

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

Thanks for any help! 谢谢你的帮助!

According to the specification, GZIPInputStream is a subclass of InflaterInputStream . 根据该规范, GZIPInputStream是的子类InflaterInputStream InflaterInputStream has a protected Inflater inf field that is the Inflater used for the decompression work. InflaterInputStream有一个protected Inflater inf字段,它是用于解压缩工作的Inflater Inflater.getBytesRead should be particularly useful for your purposes. Inflater.getBytesRead应该对您的目的特别有用。

Unfortunately, GZIPInputStream does not expose inf , so probably you'll have to create your own subclass and expose the Inflater , eg 不幸的是, 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM