在内存中创建一个Zip文件 [英] Create a Zip File in Memory

查看:141
本文介绍了在内存中创建一个Zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

使用使用 ByteArrayOutputStream http://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipOutputStream.html> ZipOutputStream 完成任务。

Use ByteArrayOutputStream with ZipOutputStream to accomplish the task.

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

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

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

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

现在 baos 包含您的zip文件为

now baos contains your zip file as a stream

这篇关于在内存中创建一个Zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆