【问题标题】:Is it possible to uncompress a gzipped file as it is downloading?是否可以在下载时解压缩 gzip 文件?
【发布时间】:2017-07-14 17:58:35
【问题描述】:

我想以编程方式下载一个 gzip 压缩文件并解压缩它,但我不想在解压缩之前等待它完全下载,而是想在下载时解压缩它,即即时解压缩它。这是否可能,或者 gzipped 格式禁止即时解压缩。

我当然可以使用 Java 的 GZIPInputStream 库在本地文件系统上逐部分解压缩文件,但是在本地文件系统中,我显然拥有完整的 gzip 文件。但是,如果我事先没有完整的 gzip 压缩文件,例如从互联网或云存储下载的情况,这是否可能?

【问题讨论】:

  • 是的,没关系。 gzip 与大多数其他压缩格式一样,是完全可流式传输的。

标签: java cloud gzip gzipstream


【解决方案1】:

由于您的 URL 连接是一个输入流,并且由于您创建了带有输入流的 gzipinputstream,我认为这相当简单?

public static void main(String[] args) throws Exception {
    URL someUrl = new URL("http://your.site.com/yourfile.gz");
    HttpURLConnection someConnection = (HttpUrlConnection) someUrl.openConnection();
    GZIPInputStream someStream = new GZIPInputStream(someConnection.getInputStream());
    FileOutputStream someOutputStream = new FileOutputStream("output.tar");
    byte[] results = new byte[1024];
    int count = someStream.read(results);
    while (count != -1) {
        byte[] result = Arrays.copyOf(results, count);
        someOutputStream.write(result);
        count = someStream.read(results);
    }
    someOutputStream.flush();
    someOutputStream.close();
    someStream.close();
}

【讨论】:

  • 太棒了。我会试试这个解决方案。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 2013-02-27
  • 2010-09-06
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
相关资源
最近更新 更多