Home >Java >javaTutorial >How to Avoid Undocumented Quirks When Using JarOutputStream to Create JAR Files?

How to Avoid Undocumented Quirks When Using JarOutputStream to Create JAR Files?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 08:00:27294browse

How to Avoid Undocumented Quirks When Using JarOutputStream to Create JAR Files?

Creating JAR Files Using JarOutputStream

To generate a JAR file programmatically, JarOutputStream is often employed. However, it is essential to avoid certain undocumented quirks within JarOutputStream:

1. Directories Ending with a Slash:

Directory names in JAR files must end with a '/' slash.

2. Paths Using Forward Slashes:

Use forward slashes '/' in paths, as opposed to backslashes ''.

3. No Leading Slashes in Entry Names:

Entry names should not start with a '/' slash.

Example Code with Corrections:

The following corrected code constructs a valid JAR file with a manifest file:

<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>

The above is the detailed content of How to Avoid Undocumented Quirks When Using JarOutputStream to Create JAR Files?. 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