URLClassLoader 类无法从使用下面列出的代码以编程方式创建的 jar 加载类,而当我使用jar cf %jarname% %sources%创建具有相同类的 jar 时,它工作正常。使用jar cf和JarOutputStream创建的 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();
}
}
最好的问候, 凯沙夫