Home >Java >javaTutorial >How to Properly Create a JAR File Using JarOutputStream in Java?

How to Properly Create a JAR File Using JarOutputStream in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 13:42:02978browse

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:

  • Directory names must terminate with a '/' slash.
  • Paths must use '/' slashes, not ''.
  • Entries cannot begin with a '/' slash.

Correct Approach Using JarOutputStream:

To create a JAR file with a manifest file using the correct method, follow these steps:

  1. Create a Manifest object and populate its main attributes.
  2. Create a JarOutputStream using the FileOutputStream and Manifest object.
  3. Use the add() method to recursively include files and directories into the JAR file.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn