在内存中创建一个 Zip 文件

Posted

技术标签:

【中文标题】在内存中创建一个 Zip 文件【英文标题】:Create a Zip File in Memory 【发布时间】:2014-06-30 01:00:14 【问题描述】:

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

【问题讨论】:

【参考方案1】:

使用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

【讨论】:

确保在 finally 块中调用 close() 方法,或者更好:使用 Java 7 的自动资源管理。 @Puce :我打算只显示一个 sn-p,但在您发表评论后,我觉得添加更结构化的代码会很好。感谢您的评论.. :) @BlackPanther 您能否详细说明/显示原始文件是否存在于本地目录中的详细版本。 @SleepDeprivedBulbasaur : This 链接可以帮助你。 查看这篇文章 (***.com/questions/25974354/…)。记得在 ByteArrayOutputStream 上调用 getBytes 之前关闭 ZipOutputStream。【参考方案2】:

由于 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 MergeContent contain compressZip code

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

【讨论】:

以上是关于在内存中创建一个 Zip 文件的主要内容,如果未能解决你的问题,请参考以下文章

Spring MVC - 在内存中创建一个ZIP文件,让用户下载

python 在内存中创建zip文件流

从内存中的 url 下载图像并在内存中创建 zip 存档以发送到浏览器

使用 System.IO.Compression 在内存中创建 ZIP 存档

使用System.IO.Compression在内存中创建ZIP存档

如何在python中创建一个zip文件