【问题标题】:Monitor GZip Download Progress in Java在 Java 中监控 GZip 下载进度
【发布时间】:2012-08-20 21:52:11
【问题描述】:

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

感谢您的帮助!

【问题讨论】:

  • 我正在读取GZipInputStream 下载的字节,这是未压缩的流。所以这不是下载的真实文件大小。

标签: java download gzip monitor progress


【解决方案1】:

根据规范,GZIPInputStreamInflaterInputStream 的子类。 InflaterInputStream 有一个 protected Inflater inf 字段,即用于解压工作的 InflaterInflater.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();

【讨论】:

  • 谢谢!我只需要实现一个自定义 GZIPInputStream,它可以使 getBytesRead()Inflater int 可用。
  • 谢谢,这正是我想要的!
猜你喜欢
  • 2013-10-31
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
相关资源
最近更新 更多