Appending Files to ZIP in Java
Seeking an alternative to the conventional approach of extracting, modifying, and recreating war files, you're exploring the possibility of appending files directly to an existing war file.
Native Java Support
Java 7 introduced the Zip File System, which provides the ability to add and modify files in ZIP archives without the need for manual repackaging. Using this API, you can directly write to files within ZIP files, as showcased in the following code snippet:
Map<String, String> env = new HashMap<>(); env.put("create", "true"); Path path = Paths.get("test.zip"); URI uri = URI.create("jar:" + path.toUri()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { Path nf = fs.getPath("new.txt"); try (Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) { writer.write("hello"); } }
This method bypasses the time-consuming process of extracting and recompressing the war file, resulting in significant efficiency gains.
Third-Party Libraries
While Java's native support is effective, there are also third-party libraries that offer additional functionality, such as TrueZip. TrueZip provides a comprehensive set of features for working with ZIP files, including the ability to append files and extract their contents. Other notable libraries include:
The above is the detailed content of How Can I Append Files to a ZIP Archive in Java Without Re-creation?. For more information, please follow other related articles on the PHP Chinese website!