Java.util.zip.ZipException:在ZipOutputStream中使用putNextEntry()



我将一个包含5个文件的zip文件转换为一个字节数组。我想从字节数组中输出磁盘上的zip文件。我的过程首先是将字节[]读取到ByteArrayInputStream中,然后读取到ZipInputStream中。

InputStream plainTextStream = new ByteArrayInputStream(plainText);
ZipInputStream zipInStream = new ZipInputStream(plainTextStream);

我想把它输出到我磁盘上的一个zip文件中,所以在这里我想我需要一个文件和一个传递该zip文件的ZipOutPutStream。

ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(file));

使用zip条目,我遍历ZipInPutStream,使用缓冲区将每个条目写入FileOutputStream。在每个主循环的末尾,我将一个条目放入ZipOutPutStream。

ZipEntry entry = null;
while((entry = zipInStream.getNextEntry()) != null){
FileOutputStream fileOutStream = new FileOutputStream(entry.getName());
byte[] byteBuff = new byte[1024];
int bytesRead = 0;
while ((bytesRead = zipInStream.read(byteBuff)) != -1)
{
fileOutStream.write(byteBuff, 0, bytesRead);
}
fileOutStream.close();
zipOutStream.putNextEntry(entry);
zipInStream.closeEntry();
}

我从zip中添加了第一个文件(有5个文件(,但当试图添加第二个文件时,我在上遇到了一个错误

zipOutStream.putNextEntry(entry)
java.util.zip.ZipException: invalid entry size (expected 18401 but got 0 bytes)

通过调试,我不知道哪里出了问题。我想这可能与放入第一个outputstream(entry.getName(((时的缓冲区有关?bytesRead while循环可能存在问题。这一切都是假设逻辑是合理的。我希望我能找到解决这个错误的办法。

您永远不会将压缩文件的内容写入zip输出流。

您不需要将输出写入文件流,只需将其直接写入zip输出流即可。

您应该使用try with resources。

try (ZipInputStream zipInStream = new ZipInputStream(new ByteArrayInputStream(plainText));
ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(file));
) {
byte[] byteBuff = new byte[1024];
for (ZipEntry entry; (entry = zipInStream.getNextEntry()) != null; ) {
zipOutStream.putNextEntry(entry);
for (int bytesRead; (bytesRead = zipInStream.read(byteBuff)) != -1; ) {
zipOutStream.write(byteBuff, 0, bytesRead);
}
}
}

不需要调用closeEntry()

要解决(预期18401,但得到0字节(

创建一个新的空白excel文件。

在步骤1中将从zip复制的文件中的数据复制到新创建的文件中。

使用新文件,它应该像它为我工作一样工作。

谢谢。

最新更新