java 压缩 InputStream,返回 InputStream(在内存中,没有文件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17928045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Zipping InputStream, returning InputStream (in memory, no file)
提问by user1156544
I am trying to do compress an InputStream and return an InputStream:
我正在尝试压缩 InputStream 并返回 InputStream:
public InputStream compress (InputStream in){
// Read "in" and write to ZipOutputStream
// Convert ZipOutputStream into InputStream and return
}
I am compressing one file (so I could use GZIP) but will do more in future (so I opted for ZIP). In most of the places:
我正在压缩一个文件(所以我可以使用 GZIP)但将来会做更多(所以我选择了 ZIP)。在大多数地方:
How can I convert ZipInputStream to InputStream?
They use toBytesArray() or getBytes() which do not exist (!) - ZipOutputStream
如何将 ZipInputStream 转换为 InputStream?
他们使用不存在的 toBytesArray() 或 getBytes() (!) - ZipOutputStream
My problems are:
我的问题是:
How do I convert the ZipOutPutStream into InputStream if such methods don't exist?
When creating the ZipOutPutStream() there is no default constructor. Should I create a new ZipOutputStrem(new OutputStream() ) ??
如果此类方法不存在,如何将 ZipOutPutStream 转换为 InputStream?
创建 ZipOutPutStream() 时没有默认构造函数。我应该创建一个新的 ZipOutputStrem(new OutputStream()) 吗??
采纳答案by user1156544
- Solved it with a ByteArrayOutputStream which has a .toByteArray()
- Same here, passing the aforementioned element
- 用具有 .toByteArray() 的 ByteArrayOutputStream 解决了它
- 同样在这里,传递上述元素
回答by soda
Something like that:
类似的东西:
private InputStream compress(InputStream in, String entryName) throws IOException {
final int BUFFER = 2048;
byte buffer[] = new byte[BUFFER];
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
zos.putNextEntry(new ZipEntry(entryName));
int length;
while ((length = in.read(buffer)) >= 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
zos.close();
return new ByteArrayInputStream(out.toByteArray());
}