使用Java组合压缩的Gzip文本文件

时间:2015-02-17 09:21:11

标签: java gzip zcat

我的问题可能与Java没有完全相关,但我目前正在寻找一种方法来组合几个压缩(gzip)文本文件,而无需手动重新压缩它们。假设我有4个文件,所有文本都是使用gzip压缩的,并希望将这些文件压缩成一个* .gz文件,而无需de +重新压缩它们。我当前的方法是打开一个InputStream并按行解析文件,存储在GZIPoutputstream中,但是工作速度非常快......我当然也可以调用

    zcat file1 file2 file3 | gzip -c > output_all_four.gz

这也可行,但也不是很快。

我的想法是复制输入流并直接将其写入输出流而不用解析"流,因为我不需要实际操纵任何东西。这样的事情可能吗?

2 个答案:

答案 0 :(得分:2)

在下面找到一个简单的Java解决方案(它与我的cat ...示例相同)。省略了输入/输出的任何缓冲以保持代码的纤薄。

public class ConcatFiles {

    public static void main(String[] args) throws IOException {
        // concatenate the single gzip files to one gzip file
        try (InputStream isOne = new FileInputStream("file1.gz");
                InputStream isTwo = new FileInputStream("file2.gz");
                InputStream isThree = new FileInputStream("file3.gz");
                SequenceInputStream sis =  new SequenceInputStream(new SequenceInputStream(isOne, isTwo), isThree);
                OutputStream bos = new FileOutputStream("output_all_three.gz")) {
            byte[] buffer = new byte[8192];
            int intsRead;
            while ((intsRead = sis.read(buffer)) != -1) {
                bos.write(buffer, 0, intsRead);
            }
            bos.flush();
        }

        // ungezip the single gzip file, the output contains the
        // concatenated input of the single uncompressed files 
        try (GZIPInputStream gzipis = new GZIPInputStream(new FileInputStream("output_all_three.gz"));
                OutputStream bos = new FileOutputStream("output_all_three")) {
            byte[] buffer = new byte[8192];
            int intsRead;
            while ((intsRead = gzipis.read(buffer)) != -1) {
                bos.write(buffer, 0, intsRead);
            }
            bos.flush();
        }
    }
}

答案 1 :(得分:1)

如果您只需要压缩许多压缩文件,上面的方法就有效。在我的情况下,我做了一个Web servlet,我的响应是20-30 KB。所以我发送了压缩响应。

我尝试在服务器启动时压缩所有单独的JS文件,然后使用上述方法添加动态代码运行时。我可以在我的日志文件中打印整个响应,但chrome只能解压缩第一个文件。休息输出以字节为单位。

经过研究后,我发现使用chrome是不可能的,并且他们已经关闭了这个bug而没有解决它。

https://bugs.chromium.org/p/chromium/issues/detail?id=20884