Java: ZipOutputStream to compress chunks of data to single zip file

丶灬走出姿态 提交于 2019-12-23 05:43:06

问题


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.

来源:https://stackoverflow.com/questions/58289073/java-zipoutputstream-to-compress-chunks-of-data-to-single-zip-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!