gpt4 book ai didi

Java ZipInputStream 提取错误

转载 作者:行者123 更新时间:2023-11-29 08:36:48 27 4
gpt4 key购买 nike

下面是一些从仅包含一个文件的 zip 文件中提取文件的代码。但是,提取的文件与通过 WinZip 或其他压缩实用程序提取的同一文件不匹配。如果文件包含奇数个字节,我预计它可能会关闭一个字节(因为我的缓冲区大小为 2,一旦读取失败我就中止)。但是,在分析(使用 WinMerge 或 Diff)使用以下代码提取的文件与通过 Winzip 提取的文件时,Java 提取中有几个区域缺少字节。有谁知道为什么或如何解决这个问题?

package zipinputtest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipInputStream;

public class test2 {
public static void main(String[] args) {
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream("C:\\temp\\sample3.zip"));
File outputfile = new File("C:\\temp\\sample3.bin");
OutputStream os = new BufferedOutputStream(new FileOutputStream(outputfile));
byte[] buffer2 = new byte[2];
zis.getNextEntry();
while(true) {
if(zis.read(buffer2) != -1) {
os.write(buffer2);
}
else break;
}
os.flush();
os.close();
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

我能够使用此图像产生错误(将其保存并压缩为 sample3.zip 并在其上运行代码),但任何足够大的二进制文件都应该显示差异。

enter image description here

最佳答案

while (true) {
if(zis.read(buffer2) != -1) {
os.write(buffer2);
}
else break;
}

常见问题。你忽略了计数。应该是:

int count;
while ((count = zis.read(buffer2)) != -1)
{
os.write(buffer2, 0, count);
}

注意:

  1. 缓冲区大小为 2 是荒谬的。使用 8192 或更多。
  2. flush() before close() 是多余的。

关于Java ZipInputStream 提取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43508690/

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