URLClassLoader类无法从使用下面列出的代码创建的jar加载类,而当我使用jar、cf %jarname% %创建具有相同类的jar时,它工作得很好。使用JarOutputStream.和jar cf创建的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();
}
}向你问好,凯沙夫
发布于 2012-07-10 14:31:25
jar命令使用JarOutputStream创建JAR文件(源代码),因此它本身不可能是该类的错误。但是,您可能忽略了JAR创建过程中的一些重要步骤。例如,您可能包含了一个格式错误的清单。
您应该能够将您的代码与jar命令的源代码进行比较,以确定您是否遗漏了一些重要的内容。
https://stackoverflow.com/questions/11415336
复制相似问题