1

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

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

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

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

4

2 回答 2

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();
        }
    }
}
于 2015-02-17T12:30:56.097 回答
1

如果您只需要 gzip 压缩许多压缩文件,则上述方法有效。在我的例子中,我制作了一个 web servlet,我的响应是 20-30 KB。所以我发送了压缩回复。

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

经过研究,我发现这在 chrome 中是不可能的,他们也已经关闭了这个错误,但没有解决它。

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

于 2016-06-17T04:58:49.867 回答