我正在编写一个java程序,它接受我生成的.class文件和Jars,然后使用类加载器将它们加载到内存中。
我目前有一个工作的jarring系统,代码为:
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
currentCatIndex: 0,
getCurrentCat: function() {
return this.cats[this.currentCatIndex];
}
}
console.log(model.getCurrentCat());
引用代码中的内容:
public static int BUFFER_SIZE = 10240;
protected static void createJarArchive(File archiveFile, File[] tobeJared) {
try {
byte buffer[] = new byte[BUFFER_SIZE];
// Open archive file
FileOutputStream stream = new FileOutputStream(archiveFile);
JarOutputStream out = new JarOutputStream(stream, new Manifest());
for (int i = 0; i < tobeJared.length; i++) {
if (tobeJared[i] == null || !tobeJared[i].exists()
|| tobeJared[i].isDirectory())
continue; // Just in case...
System.out.println("Adding " + tobeJared[i].getName());
// Add archive entry
JarEntry jarAdd = new JarEntry(getPackageNameModified +tobeJared[i].getName());
jarAdd.setTime(tobeJared[i].lastModified());
out.putNextEntry(jarAdd);
// Write file to archive
FileInputStream in = new FileInputStream(tobeJared[i]);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
}
out.close();
stream.close();
System.out.println("Adding completed OK");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error: " + ex.getMessage());
}
}
但是,当我将jar加载到内存中时,我收到错误:
getPackageNameModified = com\Test
我正在使用一个squoop类加载器来执行此操作。
AKA:
Could not load jar C:\Users\Dalton\AppData\Local\Temp\Test.jar into JVM. (Could not find class com.Test.ObjectFactory.)
使用以下命令行,类加载器代码正常工作,但我想避免在java程序中使用命令行:
ClassLoaderStack.addJarFile(jarFileAbsolute, absoluteClass);
答案 0 :(得分:0)
以下解决了我的问题:
try
{
byte buffer[] = new byte[BUFFER_SIZE];
// Open archive file
FileOutputStream stream = new FileOutputStream(archiveFile);
JarOutputStream out = new JarOutputStream(stream, new Manifest());
for (int i = 0; i < tobeJared.length; i++)
{
if (tobeJared[i].toString().endsWith(CLASS))
{
// the .replace \\ with / is a java JDK bug that requires all
// paths to use / and end in / for a jar to properly be made
LOG.info("Adding "
+ getPackageNameModified().replace(
DOUBLE_BACKSLASH, FORWARD_SLASH) + FORWARD_SLASH + tobeJared[i].getName()
+ " to the temporary JAR.");
// Add archive entry
JarEntry jarAdd = new JarEntry(
getPackageNameModified().replace(DOUBLE_BACKSLASH,
FORWARD_SLASH) + FORWARD_SLASH + tobeJared[i].getName());
jarAdd.setTime(tobeJared[i].lastModified());
out.putNextEntry(jarAdd);
// Write file to archive
FileInputStream in = new FileInputStream(tobeJared[i]);
while (true)
{
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0) break;
out.write(buffer, 0, nRead);
}
in.close();
}
}
out.close();
stream.close();
LOG.info("Adding complete --> Success");
}
catch (Exception ex)
{
ex.printStackTrace();
LOG.error("Error: " + ex.getMessage());
}
问题是在java中\是一个bug。所有目录拆分使用/替换,并以/结尾。我不知道为什么会出现这个问题,但由于这个原因,生成的JAR可以加载类。