在内存中创建一个Zip文件

我正在尝试压缩文件(例如foo.csv)并将其上传到服务器。 我有一个工作版本,它创建一个本地副本,然后删除本地副本。 我如何压缩文件,以便在不写入硬盘的情况下将其发送到纯粹的内存中?

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

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

由于在Java SE 7中引入的NIO.2 API支持自定义文件系统,您可以尝试组合内存文件系统,如https://github.com/marschall/memoryfilesystem和Oracle提供的Zip文件系统。

注意:我已经编写了一些实用程序类来使用Zip文件系统。

该库是开源的,它可能有助于您入门。

这是教程: http : //softsmithy.sourceforge.net/lib/0.4/docs/tutorial/nio-file/index.html

您可以从这里下载该库: http : //sourceforge.net/projects/softsmithy/files/softsmithy/v0.4/

或者与Maven:

  org.softsmithy.lib softsmithy-lib-core 0.4