Getting Resources from a jar: classloader vs class

2019-07-17 06:10发布

问题:

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