我正在尝试从尚未加载的第二个 JAR 加载资源(纯文本文件)。该资源将包含一个字符串,表示我计划使用的第二个 jar 中的一个类。
我无法找到加载此资源的正确方法,之前的类似问题也没有让我更进一步。这是我正在使用的:
public void readResource() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
}
我可以在这个 ClassLoader(最终成为 WebappClassLoader)中看到目录中的 jar 列表:
jarNames: [com.mysql.jdbc.jar, productivity-common.jar]
jarPath: /WEB-INF/lib
当我尝试使用 ClassLoader 加载文件时,出现 NullPointerException:
String path = loader.getResource("com/productivity/common/META-INF/providers/hello.txt").getPath();
如果这行得通,我的下一步将是使用 InputStream 读取此文件中的值,并尝试从同一个第二个 jar 创建一个与该值匹配的类的新实例。根据我正在阅读的内容,我会使用该类的路径并使用 Class.forName("value").newInstance(),但我也不确定这是正确的。
如有任何帮助,我们将不胜感激。我正在尝试了解 ClassLoaders 的工作原理并编写这个(应该很简单的)项目来提供帮助。
最佳答案
假设您有两个同名“spring/label.properties”的资源文件存储在两个不同的 jar 文件中。
您可以使用以下代码从类路径中查找所有文件的列表,然后根据路径进行过滤。
Enumeration<URL> en = this.getClass().getClassLoader().getResources("spring/label.properties");
while(en.hasMoreElements()){
URL url = en.nextElement();
//Print all path to visualize the path
System.out.println(url.getPath());
if(url.getPath().contains("my-jar")){ // This can be jar name
BufferedReader reader = new BufferedReader(new InputStreamReader(en.nextElement().openStream()));
String str = null;
while((str = reader.readLine())!=null){
// Now you can do anything with the content.
System.out.println(str);
}
}
}
这有帮助吗?
关于java - 从另一个尚未加载的 JAR 加载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591590/