3

I am trying to copy a zipped bytes array to another one using ZipOutputStream/ZipIntputStream, but it seems that the result array is not equal the original one, why is that wrong?

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();
}

Solved by updated CRC of the modified entry as follow:-

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());
sinsuren
  • 1,745
  • 2
  • 23
  • 26

0 Answers0