在内存中创建Zip文件

42

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

3个回答

96

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

现在,baosstream 的形式包含了你的 zip 文件。


确保在finally块中调用close()方法,或者更好的方法是使用Java 7的自动资源管理。 - Puce
@Puce:我本意只想展示一小段代码,但在看到你的评论后,我觉得加入更有结构的代码会更好。感谢你的评论.. :) - Thirumalai Parthasarathi
@BlackPanther,你能否详细说明一下,如果原始文件存在于本地目录中,能否展示一个详细版本。 - Sleep Deprived Bulbasaur
@SleepDeprivedBulbasaur:这个链接可以帮助你解决这个问题。 - Thirumalai Parthasarathi
8
请查看这篇文章(https://dev59.com/NYPba4cB1Zd3GeqPup1p)。在对 ByteArrayOutputStream 进行 getBytes 操作之前,请记得先关闭 ZipOutputStream。 - hencrice
显示剩余2条评论

4
随着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:
<dependency>  
    <groupId>org.softsmithy.lib</groupId>  
    <artifactId>softsmithy-lib-core</artifactId>  
    <version>0.4</version>   
</dependency>  

3

nifi 合并内容 包含 压缩Zip 代码

commons-io

public byte[] compressZip(ByteArrayOutputStream baos,String entryName) throws IOException {
    try (final ByteArrayOutputStream zipBaos = new ByteArrayOutputStream();
         final java.util.zip.ZipOutputStream out = new ZipOutputStream(zipBaos)) {
        final ZipEntry zipEntry = new ZipEntry(entryName);
        zipEntry.setSize(baos.size());
        out.putNextEntry(zipEntry);
        IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), out);
        out.closeEntry();
        out.finish();
        out.flush();
        return zipBaos.toByteArray();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接