【问题标题】:Zipping InputStream, returning InputStream (in memory, no file)压缩 InputStream,返回 InputStream(在内存中,无文件)
【发布时间】:2013-07-29 11:30:37
【问题描述】:

我正在尝试压缩一个 InputStream 并返回一个 InputStream:

public InputStream compress (InputStream in){
  // Read "in" and write to ZipOutputStream
  // Convert ZipOutputStream into InputStream and return
}

我正在压缩一个文件(所以我可以使用 GZIP),但将来会做更多事情(所以我选择了 ZIP)。在大多数地方:

我的问题是:

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

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

【问题讨论】:

  • This 应该会有所帮助。
  • 感谢 Boris the Spider,但这仅显示 ZIP 文件的操作,我知道。我认为我缺少一些基本的 Java I/O,而不是如何压缩它们

标签: java zip


【解决方案1】:
  1. 使用具有 .toByteArray() 的 ByteArrayOutputStream 解决它
  2. 这里也一样,传递了上述元素

【讨论】:

    【解决方案2】:

    类似的东西:

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

    【讨论】:

    • 只是一个小提示:在while语句中,你应该检查in.read(buffer) >= 0。因为如果输入流没有准备好,它可能会返回0字节读取,但是end 没有到达,流可能稍后准备好。所以它不应该被认为是完成,直到它返回 -1
    • 是否可以使用 GZIP 做同样的事情?
    猜你喜欢
    • 1970-01-01
    • 2012-06-17
    • 2023-03-22
    • 2015-11-12
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2011-01-02
    相关资源
    最近更新 更多