gpt4 book ai didi

java - 压缩 InputStream,返回 InputStream(在内存中,没有文件)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:19 30 4
gpt4 key购买 nike

我正在尝试压缩一个 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() ) 吗??

最佳答案

类似的东西:

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

关于java - 压缩 InputStream,返回 InputStream(在内存中,没有文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17928045/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com