编辑内容后Zip文件夹已损坏

时间:2016-02-12 23:00:23

标签: java io outputstream zipinputstream zipoutputstream

我正在尝试使用ZipOutputStream / ZipIntputStream将压缩的字节数组复制到另一个,但似乎结果数组与原始数组不相同,为什么会出错?

public static void main(String[] args) throws IOException {
    File file = new File("folder.zip");
    byte[] bFile = new byte[(int) file.length()];

    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    fileInputStream.close();
    byte[] aFile = copyZippedFileBytes(bFile);
    System.out.println(Arrays.equals(aFile, bFile));
}

public static byte[] copyZippedFileBytes(byte[] arr) throws IOException {

    ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(arr));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(baos);

    ZipEntry entry;
    while ((entry = zipStream.getNextEntry()) != null) {
        zipOutputStream.putNextEntry(entry);
        // assume files are small
        byte[] indexFileByte = new byte[(int) entry.getSize()];
        zipStream.read(indexFileByte);

        zipOutputStream.write(indexFileByte);
        zipOutputStream.closeEntry();
    }
    zipOutputStream.close();
    zipStream.close();
    return baos.toByteArray();
}

通过修改条目的更新CRC解决如下: -

CRC32 crc = new CRC32();         crc.reset();

    BufferedInputStream bis = new BufferedInputStream
        (new ByteArrayInputStream(data));

    int bytesRead;
    byte[] buffer = new byte[1024];

    while ((bytesRead = bis.read(buffer)) != -1) {
        crc.update(buffer, 0, bytesRead);
    }

    entry.setMethod(ZipEntry.STORED);
    entry.setCompressedSize(data.length);
    entry.setSize(data.length);
    entry.setCrc(crc.getValue());

0 个答案:

没有答案