java:更改ZipEntry名称

我有以下代码将文本文件写入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的文件名(因为它的名称将取决于其编写的内容)。

此外,只有在最终文件名已知时才能写入缓冲区并写入文件(因为文件大小可能非常大:内存不足)。

任何有关如何做到这一点的建议将不胜感激!

谢谢,托马斯

这是一个缺少的function,可能很简单,因为条目本身不会被压缩。

zip文件系统是最简单的方法,需要重写:自java 7以来,您可以使用zip文件作为虚拟文件系统:在其中编写,重命名和移动文件。 一个例子 。 您将文件从普通文件系统复制到zip文件系统,然后在zip中重命名该文件。

 // Create the zip file: URI zipURI = URI.create("jar:file:" + fullFilename); // "jar:file:/.../... .zip" Map 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文件? 最后一步可以删除您在磁盘上创建的文件。