在内存中创建一个Zip文件

Sle*_*aur 29 java memory zip inputstream

我正在尝试压缩文件(例如foo.csv)并将其上传到服务器.我有一个工作版本,它创建一个本地副本,然后删除本地副本.我如何压缩文件,以便我可以发送它而无需写入硬盘驱动器并完全在内存中执行?

Thi*_*thi 73

使用ByteArrayOutputStreamZipOutputStream来完成任务.

您可以使用ZipEntry指定要包含在zip文件中的文件.

以下是使用上述类的示例,

String s = "hello world";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {

  /* File is not on the disk, test.txt indicates
     only the file name to be put into the zip */
  ZipEntry entry = new ZipEntry("test.txt"); 

  zos.putNextEntry(entry);
  zos.write(s.getBytes());
  zos.closeEntry();

  /* use more Entries to add more files
     and use closeEntry() to close each file entry */

  } catch(IOException ioe) {
    ioe.printStackTrace();
  }
Run Code Online (Sandbox Code Playgroud)

现在baos包含您的zip文件作为stream

  • 查看这篇文章(http://stackoverflow.com/questions/25974354/creating-zip-file-in-memory-out-of-byte-zip-file-is-allways-corrupted).记得在ByteArrayOutputStream上调用`getBytes`之前关闭ZipOutputStream. (4认同)