Java ZipInputStream提取错误 [英] Java ZipInputStream extraction errors

查看:121
本文介绍了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:

  1. 2的缓冲区大小是荒谬的.使用8192或更多.
  2. close()之前的
  3. flush()是多余的.
  1. A buffer size of 2 is ridiculous. Use 8192 or more.
  2. flush() before close() is redundant.

这篇关于Java ZipInputStream提取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆