"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid Undocumented Quirks When Using JarOutputStream to Create JAR Files?

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

Published on 2025-01-27
Browse:450

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:

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();
        }
    }
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3