【问题标题】:Convert zip file to gzip and write to hdfs [duplicate]将zip文件转换为gzip并写入hdfs [重复]
【发布时间】:2019-02-14 16:02:46
【问题描述】:

我有一个 zip 文件,我想将其转换为 gzip 并将其写回文件系统。我该怎么做?

我已经有了将文件压缩为 gzip 的代码:

private static void compressGzipFile(String file, String gzipFile) {
    try {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(gzipFile);
        GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
        byte[] buffer = new byte[1024];
        int len;

        while ((len=fis.read(buffer)) != -1) {
            gzipOS.write(buffer, 0, len);
        }

        // Close resources
        gzipOS.close();
        fos.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

现在我需要将 zip 文件转换为 gzip 文件的代码。

【问题讨论】:

  • 您无法将 zip 文件转换为 gzip 文件,因为 zip 文件可以包含文件,而 gzip 不能。您是否要改为 gzip 压缩文件(我怀疑这会有效)。

标签: java hadoop hdfs gzip


【解决方案1】:

为什么不将ZipInputStream 直接通过管道传递给GZIPOutputStream

private static void convertZipToGzip(String zipFile, String gzipFile) {
    try (ZipInputStream zipIS = new ZipInputStream(file),
         GZIPOutputStream gzipOS = new GZIPOutputStream(gzipFile)) {
        zipIS.transferTo(gzipOS);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

此解决方案利用了 Java 9 非常有用的 InputStream#transferTo(OutputStream)。如果您尚未使用 Java 9,则需要手动将字节从一个流复制到另一个流,或使用 Apache Commons IOUtils 的IOUtils.copy(InputStream, OutputStream)

【讨论】:

  • 答案中的代码获取 zip 文件并将其压缩为 gzip,我正在寻找获取 zip 内容并将其压缩到 gzip 的代码
猜你喜欢
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
  • 2016-12-30
  • 2012-06-16
  • 2018-08-23
  • 1970-01-01
相关资源
最近更新 更多