3

我正在尝试使用 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 = 新的 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());
4

0 回答 0