Creating JAR files programmatically using java.util.jar.JarOutputStream often leads to inconsistencies. While the produced JAR files may appear valid and extractable, they face issues when loading libraries. Despite containing the required files, Java fails to locate them. This discrepancy between programmatically generated JAR files and those created using Sun's jar command-line tool necessitates an understanding of the underlying problem.
Investigating the intricacies of JarOutputStream reveals three undocumented quirks that play a crucial role in successful JAR file creation:
To address these quirks and create JAR files correctly, the following code demonstrates the appropriate approach:
<code class="java">public void run() throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); 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); entry.setTime(source.lastModified()); target.putNextEntry(entry); target.closeEntry(); for (File nestedFile : source.listFiles()) { add(nestedFile, target); } } else { JarEntry entry = new JarEntry(name); entry.setTime(source.lastModified()); target.putNextEntry(entry); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) { byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); } } }</code>
By adhering to these guidelines, programmatically generated JAR files will accurately reflect their contents and eliminate loading issues encountered when extracting or using them.
The above is the detailed content of Why Do JAR Files Created with `JarOutputStream` Fail to Load Libraries?. For more information, please follow other related articles on the PHP Chinese website!