0

URLClassLoader 类无法从使用下面列出的代码以编程方式创建的 jar 加载类,而当我使用jar cf %jarname% %sources%创建具有相同类的 jar 时,它工作正常。使用jar cfJarOutputStream创建的 jar 之间是否有区别。

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

最好的问候, 凯沙夫

4

1 回答 1

1

jar命令用于JarOutputStream创建一个 JAR 文件(源代码),因此它不能是该类本身的错。但是,您可能错过了 JAR 创建过程中的一些重要步骤。例如,您可能包含了格式错误的清单。

您应该能够将您的代码与jar命令的源代码进行比较,看看您是否遗漏了一些重要的东西。

于 2012-07-10T14:31:25.000 回答