使用gzip压缩InputStream [英] Compress an InputStream with gzip
问题描述
我想使用Gzip压缩在java中压缩输入流。
I would like to compress an input stream in java using Gzip compression.
假设我们有一个未压缩的输入流(1GB数据..)。我想要一个来自源的压缩输入流:
Let's say we have an input stream (1GB of data..) not compressed. I want as a result a compressed inputstream from the source :
public InputStream getCompressedStream(InputStream unCompressedStream) {
// Not working because it's uncompressing the stream, I want the opposite.
return new GZIPInputStream(unCompressedStream);
}
推荐答案
压缩数据需要 GZIPOutputStream
。但是,由于您需要像从InputStream那样读取数据,因此需要将OutputStream转换为InputStream。您可以使用getBytes()来执行此操作:
To compress data you need the GZIPOutputStream
. But since you need to read the data back as if from an InputStream you need to convert the OutputStream to an InputStream. You can use getBytes() to do so:
GZIPOutputStream gout = new GZIPOutputStream(out);
//... Code to read from your original uncompressed data and write to out.
//Convert to InputStream.
new ByteArrayInputStream(gout.getBytes());
但是这种方法有一个限制,你需要首先读入所有数据 - 这意味着你有有足够的内存来保存缓冲区。
But this method has the limitation that you need to read in all data first - and that means you have to have enough memory to hold that buffer.
此线程中提到了使用管道的替代方法 - 如何将OutputStream转换为InputStream?
Alternative approaches using Pipes are mentioned in this thread - How to convert OutputStream to InputStream?
这篇关于使用gzip压缩InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!