Creating JAR Files with JarOutputStream: Troubleshooting Hidden Quirks
Although the JarOutputStream utility appears straightforward for creating JAR files programmatically, it harbors several undocumented quirks that can compromise the integrity of generated archives. These quirks manifest in three specific areas:
To ensure proper JAR creation, adhere to the following guidelines:
<code class="java">public void run() throws IOException { Manifest manifest = new Manifest(); // ... (populate manifest) JarOutputStream target = new JarOutputStream( new FileOutputStream("output.jar"), manifest ); add(new File("inputDirectory"), target); target.close(); } private void add(File source, JarOutputStream target) throws IOException { String name = source.getPath().replace("\", "/"); if (source.isDirectory()) { if (!name.endsWith("/")) { name += "/"; } JarEntry entry = new JarEntry(name); // ... (set entry properties) target.putNextEntry(entry); target.closeEntry(); for (File nestedFile : source.listFiles()) { add(nestedFile, target); } } else { JarEntry entry = new JarEntry(name); // ... (set entry properties) target.putNextEntry(entry); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) { // ... (write file to JAR entry) } target.closeEntry(); } }</code>
By adhering to these guidelines, you can accurately create JAR files that will extract and function as intended.
The above is the detailed content of How to Avoid Hidden Quirks When Creating JAR Files with JarOutputStream?. For more information, please follow other related articles on the PHP Chinese website!