开发者

Getting Resources from a jar: classloader vs class resourceasstream

开发者 https://www.devze.com 2023-04-08 00:07 出处:网络
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.

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?


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号