Java 在内存中创建一个 Zip 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23612864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:19:07  来源:igfitidea点击:

Create a Zip File in Memory

javamemoryzipinputstream

提问by Sleep Deprived Bulbasaur

I'm trying to zip a file (for example foo.csv) and upload it to a server. I have a working version which creates a local copy and then deletes the local copy. How would I zip a file so I could send it without writing to the hard drive and do it purely in memory?

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

采纳答案by Thirumalai Parthasarathi

Use ByteArrayOutputStreamwith ZipOutputStreamto accomplish the task.

使用ByteArrayOutputStreamZipOutputStream来完成任务。

you can use ZipEntryto specify the files to be included into the zip file.

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

Here is an example of using the above classes,

这是使用上述类的示例,

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

now baoscontains your zip file as a stream

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

回答by Puce

As the NIO.2 API, which was introduce in Java SE 7, supports custom file systems you could try to combine an in-memory filesystem like https://github.com/marschall/memoryfilesystemand the Zip file system provided by Oracle.

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

Note: I've written some utility classes to work with the Zip file system.

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

The library is Open Source and it might help to get you started.

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

Here is the tutorial: http://softsmithy.sourceforge.net/lib/0.4/docs/tutorial/nio-file/index.html

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

You can download the library from here: http://sourceforge.net/projects/softsmithy/files/softsmithy/v0.4/

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

Or with Maven:

或者使用 Maven:

<dependency>  
    <groupId>org.softsmithy.lib</groupId>  
    <artifactId>softsmithy-lib-core</artifactId>  
    <version>0.4</version>   
</dependency>