1

Follow up of Question: Java: how to compress a byte[] using ZipOutputStream without intermediate file

I can zip data without an intermediate file (or memory file). I now need to zip chunks of data and add them to a single zip file.

I am using a single ZipOutputStream as suggested in the previous question.

String infile = "test.txt";
FileInputStream in = new FileInputStream(infile);

String outfile = "test.txt.zip";
FileOutputStream out = new FileOutputStream(outfile);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry("test_unzip.txt");
entry.setSize(2048);
zos.putNextEntry(entry);

int len = 0;
while (len > -1) {
      byte[] buf = new byte[10];
      len = in.read(buf);
      zos.write(buf);
      out.write(baos.toByteArray());
      baos.reset();
}

zos.closeEntry();
zos.finish();
zos.close();

in.close();
out.close();

I have tried different sizes for buf, reordering zos.finish and zos.closeEntry, and also tried with and without baos.reset.

I have also tried reading the entire contents of infile into a single buf but still not working.

I expected a valid .zip file that will unzip into test_unzip.txt. However, when i try unzip test.txt.zip on my command line i get the following error:

End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of test.txt.zip or
        test.txt.zip.zip, and cannot find test.txt.zip.ZIP, period.
  • Have you looked at examples like https://www.baeldung.com/java-compress-and-uncompress ? – Louis Wasserman Oct 08 '19 at 18:37
  • @Louis Wasserman Thanks again for your quick reply. yes, i had tried the example which does `ZipOutputStream(FileOutputStream)` and it works perfectly! But I need to use `ZipOutputStream(ByteArrayOutputStream)`. This is because as mentioned in the previous question, i need `byte[] compress(byte[])` implemented using ZipOutputStream internally. – Lakshmi Manasa Oct 08 '19 at 22:02

0 Answers0