Home >Java >javaTutorial >How to Properly Create a JAR File Using JarOutputStream in Java?
Creating a JAR File Using JarOutputStream
This article addresses the creation of JAR files programmatically using Java's java.util.jar.JarOutputStream class. While the JAR file created may appear correct initially, it can fail to load libraries when used. The reason lies in certain undocumented quirks of JarOutputStream.
Quirks of JarOutputStream:
Correct Approach Using JarOutputStream:
To create a JAR file with a manifest file using the correct method, follow these steps:
add() Method:
<code class="java">private void add(File source, JarOutputStream target) throws IOException { String name = source.getPath().replace("/", "/"); // Ensure path uses '/' slash if (source.isDirectory()) { if (!name.endsWith("/")) { name += "/"; // Add trailing '/' for directories } 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 following these guidelines, you can create JAR files programmatically using JarOutputStream that are compatible with other Java tools.
The above is the detailed content of How to Properly Create a JAR File Using JarOutputStream in Java?. For more information, please follow other related articles on the PHP Chinese website!