我试图压缩文件(例如foo.csv)并将其上传到服务器。我有一个工作版本,它创建一个本地副本,然后删除本地副本。我如何压缩文件以便我可以在不写入硬盘的情况下发送文件并将其完全记录在内存中?
答案 0 :(得分:64)
使用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
答案 1 :(得分:3)
由于在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>
答案 2 :(得分:2)
nifi MergeContent contain compressZip code
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();
}
}