[英]Create a Zip File in Memory
我正在尝试压缩文件(例如 foo.csv)并将其上传到服务器。 我有一个工作版本,它创建一个本地副本,然后删除本地副本。 我将如何压缩文件以便我可以在不写入硬盘驱动器的情况下发送它并纯粹在内存中执行?
使用ByteArrayOutputStream和ZipOutputStream来完成任务。
您可以使用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:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-core</artifactId>
<version>0.4</version>
</dependency>
nifi MergeContent 包含 compressZip 代码
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.