Java ZipInputStream提取错误
下面是一些代码,该代码从仅包含一个文件的zip文件中提取文件.但是,提取的文件与通过WinZip或其他zip实用工具提取的文件不匹配.我希望如果文件包含奇数个字节(因为我的缓冲区的大小为2,并且读取失败后我就中止),它可能会减少一个字节.但是,在分析(使用WinMerge或Diff)使用以下代码提取的文件与通过Winzip提取的文件进行分析时,在Java提取中有几个区域缺少字节.有谁知道为什么或如何解决这个问题?
Below is some code which extracts a file from a zip file containing only a single file. However, the extracted file does not match the same file extracted via WinZip or other zip utility. I expect that it might be off by a byte if the file contains an odd number of bytes (because my buffer is size 2 and I just abort once the read fails). However, when analyzing (using WinMerge or Diff) the file extracted with code below vs. file extracted via Winzip, there are several areas where bytes are missing from the Java extraction. Does anyone know why or how I can fix this?
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并在其上运行代码),但是任何大小足够的二进制文件都应显示差异.
I was able to produce the error using this image (save it and zip as sample3.zip and run the code on it), but any binary file of sufficient size should show the discrepancies.
while (true) {
if(zis.read(buffer2) != -1) {
os.write(buffer2);
}
else break;
}
常见问题.您无视计数.应该是:
Usual problem. You're ignoring the count. Should be:
int count;
while ((count = zis.read(buffer2)) != -1)
{
os.write(buffer2, 0, count);
}
NB:
- 2的缓冲区大小是荒谬的.使用8192或更多.
-
flush()
是多余的.
close()
之前的- A buffer size of 2 is ridiculous. Use 8192 or more.
-
flush()
beforeclose()
is redundant.