Home >Java >javaTutorial >How to Avoid Hidden Quirks When Creating JAR Files with JarOutputStream?

How to Avoid Hidden Quirks When Creating JAR Files with JarOutputStream?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 10:59:301070browse

How to Avoid Hidden Quirks When Creating JAR Files with JarOutputStream?

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:

  • Directory names require a trailing /, ensuring they end as known directories within the JAR.
  • Path separators must be denoted by /, not the platform-specific .
  • Entries must not start with a / slash.

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!

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