Pregunta

the URLClassLoader class fails to load classes from the jar created programatically using the code listed below, whereas when i create a jar with the same classes using jar cf %jarname% %sources% it works fine. Is there a difference between the jars created using jar cf and JarOutputStream.

public static ByteArrayInputStream createJar(File file) throws IOException {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(bytes, manifest);
    for (File child : file.listFiles()) {
        addJarEntries(child, target, "");
    }
    target.flush();
    target.close();
    return new ByteArrayInputStream(bytes.toByteArray());
}

private static void addJarEntries(File source, JarOutputStream target, String path) throws IOException {
    BufferedInputStream in = null;
    try
    {
        if (source.isDirectory())
        {
            String name = path +source.getName() + File.separator;
            for (File nestedFile: source.listFiles())
                addJarEntries(nestedFile, target, name);
            return;
        }

        in = new BufferedInputStream(new FileInputStream(source));

        JarEntry entry = new JarEntry(path + source.getName());
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        while (true)
        {
            int count = in.read(buffer);
            if (count == -1)
                break;
            target.write(buffer, 0, count);
        }
        target.closeEntry();
    }
    finally
    {
        if (in != null)
            in.close();
    }
}

Best Regards, Keshav

¿Fue útil?

Solución

The jar command uses JarOutputStream to create a JAR file (source code) so it cannot be the fault of that class per se. However, it is possible that you missed some important step in the JAR creation process. For instance, you may have included a malformed manifest.

You should be able to compare your code with the source code of the jar command to see if you have missed something important.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top