我需要創建一個jar並使用classLoader在jar中加載類。我使用下面的代碼來創建jar中的文件夾結構。這工作正常,但是當我嘗試從jar中加載類時,它會引發異常ClassNotFound。在其中創建Jar和加載類
public void createJar() throws IOException
{
//FileOutputStream stream = new FileOutputStream("D:\\MyFolder\\apache-tomcat-6.0.32\\webapps\\SpringTest\\WEB-INF\\lib\\serviceJar.jar");
FileOutputStream stream = new FileOutputStream("D:/MyFolder/apache-tomcat-6.0.32/webapps/SpringTest/WEB-INF/lib/serviceJar.jar");
JarOutputStream target = new JarOutputStream(stream, new Manifest());
add(new File("D:/myJar"), target);
target.close();
stream.close();
}
private void add(File source, JarOutputStream target) throws IOException
{
byte buffer[] = new byte[10204];
try
{
if (source.isDirectory())
{
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty())
{
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile: source.listFiles())
add(nestedFile, target);
return;
}
JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
// JarEntry entry = new JarEntry(source.getPath());
entry.setTime(source.lastModified());
target.putNextEntry(entry);
FileInputStream in = new FileInputStream(source);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
target.write(buffer, 0, nRead);
}
in.close();
target.closeEntry();
}
catch(Exception e){
}
finally
{
}
}
類是賈裏德是在位置 「d:\ myjar這一\彈簧\控制器\ MyController.class」 和 「 d:\ myjar這一\彈簧\服務\ MyService.class」。所以罐被創建爲我想,也包含文件夾結構(Mycontroller.class裏面罐子在位置\ myjar這一\彈簧\控制器)。但是當我嘗試用下面的代碼加載它,我得到異常
public void loadJar() {
//File root = new File("D:\\MyFolder\\apache-tomcat-6.0.32\\webapps\\SpringTest\\WEB-INF\\lib\\serviceJar.jar");//
File root = new File("D:/MyFolder/apache-tomcat-6.0.32/webapps/SpringTest/WEB-INF/lib/serviceJar.jar");//
URLClassLoader classLoader;
try {
classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("myJar.spring.controller.MyController", true, classLoader);
Object instance = cls.newInstance(); // Should print constructor content
System.out.println(instance);
Method m =cls.getMethod("printThis", null);
m.invoke(instance, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
但是,如果我創建罐子裏面沒有包裝結構,它工作正常。 我已經檢查過我的所有路徑,它們都是正確的.Jar內的類文件的位置也是正確的。 請解釋爲什麼我得到ClassNotFound異常。同時建議如果在createJar()或add()代碼中需要更改。
您是否檢查過創建的jar文件內容? – Sanjeev
爲什麼你沒有使用jar命令來創建jar有什麼特別的原因嗎? – BetaRide
@ Sanjeev.I檢查過jar文件內容。類文件存在於適當的位置。 – user3153309