我有以下代码,可以在 ZIP 文件中写入文本文件:
FileOutputStream fOut = new FileOutputStream(fullFilename, false);
BufferedOutputStream bOut = new BufferedOutputStream(fOut);
ZipOutputStream zOut = new ZipOutputStream(bOut);
zOut.putNextEntry(new ZipEntry("aFile1.txt"));
//Do some processing and write to zOut...
zOut.write(...);
(...)
zOut.closeEntry();
zOut.close();
//Etc (close all resources)
我需要在写入 zipEntry 后更改其文件名(因为它的名称取决于写入的内容)。
此外,仅在知道最终文件名时才写入缓冲区并写入文件不是一个选项(因为文件大小可能非常大:内存不足)。
这是一个缺失的功能,本来可以很简单,因为条目本身没有被压缩。
最简单的方法,但需要重写,是 zip 文件系统:从 java 7 开始,您可以使用 zip 文件作为虚拟文件系统:在其中写入、重命名和移动文件。一个例子。您将文件从普通文件系统复制到 zip 文件系统中,然后在 zip 中重命名该文件。
// Create the zip file:
URI zipURI = URI.create("jar:file:" + fullFilename); // "jar:file:/.../... .zip"
Map<String, Object> env = new HashMap<>();
env.put("create", "true");
FileSystem zipFS = FileSystems.newFileSystem(zipURI, env, null);
// Write to aFile1.txt:
Path pathInZipfile = zipFS.getPath("/aFile1.txt");
BufferedWriter out = Files.newBufferedWriter(pathInZipfile,
StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
out.write("Press any key, except both shift keys\n");
out.close();
// Rename file:
Path pathInZipfile2 = zipFS.getPath("/aFile2.txt");
Files.move(pathInZipfile, pathInZipfile2);
zipFS.close();
原则上您也可以保留旧代码 - 无需重命名。并使用 zip 文件系统仅用于重命名。
如何将 aFile1.txt 的内容保存到磁盘上的临时文件,重命名,然后创建 zip 文件?最后一步可以删除您在磁盘上创建的文件。