从jar获取资源:classloader vs class resourceasstream [英] Getting Resources from a jar: classloader vs class resourceasstream
问题描述
我正在尝试实现一种方法,当该方法被调用时,从加载类的jar中的特定资源获取字符串。
I am trying to implement a method that when called, get a string from a particular resource in the jar that the class is loaded from.
例如:
import mypath.myclass; //from a jar
String result = gitid.getGitId(myclass.class);
我目前正在使用:
InputStream is = null;
BufferedReader br = null;
String line;
is = c.getResourceAsStream("/com/file.text");
问题是无论我给什么班级,我都不断获得相同的资源。
The problem is I keep getting the same resource for no matter what class I give it.
我也尝试过:
is = c.getClassLoader().getResourceAsStream("/com/file.text");
这完全失败。
任何建议
此外,从类加载器与类调用getResourceAsStream和类之间有什么区别?
Also,what is the difference between calling getResourceAsStream from the class loader vs the class?
推荐答案
Class.getResourceAsStream()
获得一个 ClassLoader
实例,从 Class.getClassLoader()
调用中获得的效果几乎相同。
The Class.getResourceAsStream()
gets a ClassLoader
instance, pretty much the same you get from Class.getClassLoader()
call.
您可以做的就是获取URL对于给定的类,并替换类资源路径,即文件的路径。例如,以下代码将从同一个jar中返回资源:
What you could do, is get the URL for a given class and replace class resource path your path of your file. for example, the following code will return resource from the same jar:
Class c = String.class;
URL u = c.getResource('/' + c.getName().replace('.', '/') + ".class");
String s = u.toString();
URL url = new URL(s.substring(0, s.indexOf('!')) + "!/META-INF/MANIFEST.MF");
InputStream is = url.openStream();
您将不得不分别处理未受干扰的类文件夹。
You'll have to handle not jarred class folders separately.
这篇关于从jar获取资源:classloader vs class resourceasstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!