Getting Resources from a jar: classloader vs class resourceasstream

烈酒焚心 提交于 2019-12-24 02:39:05

问题


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.

For example:

import mypath.myclass; //from a jar
String result = gitid.getGitId(myclass.class);

On the backed I am currently using:

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.

I have also tried:

is = c.getClassLoader().getResourceAsStream("/com/file.text");

This fails completely.

Any suggestions would be much appreciated.

Also,what is the difference between calling getResourceAsStream from the class loader vs the class?


回答1:


The Class.getResourceAsStream() gets a ClassLoader instance, pretty much the same you get from Class.getClassLoader() call.

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.




回答2:


Probably all classes were loaded by the same ClassLoader instance. So as long as the path of the resource doesn't change you will get the same resource every time.

getResourceAsStream:

This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).



来源:https://stackoverflow.com/questions/7559846/getting-resources-from-a-jar-classloader-vs-class-resourceasstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!