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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:38:45  来源:igfitidea点击:

Zipping InputStream, returning InputStream (in memory, no file)

javazip

提问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)。在大多数地方:

My problems are:

我的问题是:

  1. How do I convert the ZipOutPutStream into InputStream if such methods don't exist?

  2. When creating the ZipOutPutStream() there is no default constructor. Should I create a new ZipOutputStrem(new OutputStream() ) ??

  1. 如果此类方法不存在,如何将 ZipOutPutStream 转换为 InputStream?

  2. 创建 ZipOutPutStream() 时没有默认构造函数。我应该创建一个新的 ZipOutputStrem(new OutputStream()) 吗??

采纳答案by user1156544

  1. Solved it with a ByteArrayOutputStream which has a .toByteArray()
  2. Same here, passing the aforementioned element
  1. 用具有 .toByteArray() 的 ByteArrayOutputStream 解决了它
  2. 同样在这里,传递上述元素

回答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());
}