【发布时间】:2016-12-20 16:29:13
【问题描述】:
如何正确地将字节 zip 压缩到 ByteArrayOutputStream,然后使用 ByteArrayInputStream 读取?我有以下方法:
private byte[] getZippedBytes(final String fileName, final byte[] input) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(bos);
ZipEntry entry = new ZipEntry(fileName);
entry.setSize(input.length);
zipOut.putNextEntry(entry);
zipOut.write(input, 0, input.length);
zipOut.closeEntry();
zipOut.close();
//Turn right around and unzip what we just zipped
ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()));
while((entry = zipIn.getNextEntry()) != null) {
assert entry.getSize() >= 0;
}
return bos.toByteArray();
}
当我执行这段代码时,底部的断言失败,因为entry.size 是-1。我不明白为什么提取的实体与压缩的实体不匹配。
【问题讨论】:
-
为什么?你已经有了字节。你为什么要压缩和解压缩它们只是为了取回你已经拥有的东西?
-
这只是一个示例作为概念证明。在我的实际场景中,我正在使用压缩文件的字节创建一个模拟多部分文件,以便我可以测试另一个类是否正确解压缩内容。
-
bos.toByteArray() 的大小是多少?
标签: java zip bytearrayoutputstream zipoutputstream bytearrayinputstream