I would like to know the best way of loading a resource in Java:
this.getClass().getResource() (or getResourceAsStream())
,Thread.currentThread().getContextClassLoader().getResource(name)
,System.class.getResource(name)
.
Join Stack Overflow to learn, share knowledge, and build your career.
I would like to know the best way of loading a resource in Java:
this.getClass().getResource() (or getResourceAsStream())
,Thread.currentThread().getContextClassLoader().getResource(name)
,System.class.getResource(name)
.Work out the solution according to what you want...
There are two things that getResource
/getResourceAsStream()
will get from the class it is called on...
So if you do
this.getClass().getResource("foo.txt");
it will attempt to load foo.txt from the same package as the "this" class and with the class loader of the "this" class. If you put a "/" in front then you are absolutely referencing the resource.
this.getClass().getResource("/x/y/z/foo.txt")
will load the resource from the class loader of "this" and from the x.y.z package (it will need to be in the same directory as classes in that package).
Thread.currentThread().getContextClassLoader().getResource(name)
will load with the context class loader but will not resolve the name according to any package (it must be absolutely referenced)
System.class.getResource(name)
Will load the resource with the system class loader (it would have to be absolutely referenced as well, as you won't be able to put anything into the java.lang package (the package of System).
Just take a look at the source. Also indicates that getResourceAsStream just calls "openStream" on the URL returned from getResource and returns that.
Thread#setContextClassLoader
. This is useful if you need to modify the classpath while the program is executing.
– Max
Jan 26 '16 at 17:06
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
this.getClass()
. Create an instance of the subclass and call the method... it'll print out the name of the subclass, not the superclass.
– Jon Skeet
Oct 5 '10 at 9:01
I search three places as shown below. Comments welcome.
public URL getResource(String resource){
URL url ;
//Try with the Thread Context Loader.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader != null){
url = classLoader.getResource(resource);
if(url != null){
return url;
}
}
//Let's now try with the classloader that loaded this class.
classLoader = Loader.class.getClassLoader();
if(classLoader != null){
url = classLoader.getResource(resource);
if(url != null){
return url;
}
}
//Last ditch attempt. Get the resource from the classpath.
return ClassLoader.getSystemResource(resource);
}
I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).
public class ResourceLoader {
public static URL getResource(String resource) {
final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
classLoaders.add(Thread.currentThread().getContextClassLoader());
classLoaders.add(ResourceLoader.class.getClassLoader());
for (ClassLoader classLoader : classLoaders) {
final URL url = getResourceWith(classLoader, resource);
if (url != null) {
return url;
}
}
final URL systemResource = ClassLoader.getSystemResource(resource);
if (systemResource != null) {
return systemResource;
} else {
try {
return new File(resource).toURI().toURL();
} catch (MalformedURLException e) {
return null;
}
}
}
private static URL getResourceWith(ClassLoader classLoader, String resource) {
if (classLoader != null) {
return classLoader.getResource(resource);
}
return null;
}
}
I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:
try {
InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
img = ImageIO.read(path);
} catch (IOException e) {
e.printStackTrace();
}
this.getClass().getResourceAsStream()
in this case. If you get a look at the source of the getResourceAsStream
method, you will notice that it does the same thing than you but in a smarter way (fallback if no ClassLoader
can be found on the class). It also indicates that you can encounter a potential null
on getClassLoader
in your code …
– Doc Davluz
May 26 '17 at 7:33
this.getClass().getResourceAsStream()
is not working for me, so I use that works. I think there are some people who can face with problem like mine.
– Vladislav
May 27 '17 at 23:03