Java:ZipOutputStream将数据块压缩为单个zip文件

时间:2019-10-08 15:02:09

标签: java arrays compression zipoutputstream

跟进问题:Java: how to compress a byte[] using ZipOutputStream without intermediate file

我可以压缩数据而无需中间文件(或内存文件)。现在,我需要压缩数据块并将其添加到单个zip文件中。

我正在使用上一个问题中建议的单个ZipOutputStream。

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

我为buf尝试了不同的大小,对zos.finishzos.closeEntry进行了重新排序,还尝试了有无baos.reset的情况。

我也尝试将infile的全部内容读入单个buf,但仍然无法正常工作。

我希望有一个有效的.zip文件,它将解压缩到test_unzip.txt中。 但是,当我在命令行上尝试unzip test.txt.zip时,出现以下错误:

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.

0 个答案:

没有答案