Reputation: 6735
I have the following directory structure in my java project:
This project is managed by Maven
, and when package all resources are put into a single .jar
file.
Within Utils.java
I'm loading car.jpg
, and since the texture file is on the classpath I'm using the following method to get a handle on the file:
URL url = Utils.class.getResource("/textures/car.jpg");
I've seen a lot of confusion about which method to use when getting a reference to a file on the classpath.
Is class.getResource()
the right method to use? Or does class.getResourceAsStream()
offer any benefits?
Upvotes: 4
Views: 1243
Reputation: 20059
Stay away from getResource() whenever possible. Prefer getResourceAsStream() where you can.
The main reasoning behind this rule is that new URL(URL.toString()) for resources often breaks in totally unexpected ways depending on the class loader which provided the original URL.
Unlike what it look like on first glance, two URL's of equal string representation are not treated the same, depending on how they were constructed. That isn't a problem for URL's of standardized protocols. But it is for URL's generated by a ClassLoader; a ClassLoader can provide you an URL constructed this way:
new URL(URL context, String spec, URLStreamHandler handler)
where the ClassLoader specifies its own URLStreamHandler. The handler information is lost when such an URL is ever converted to String, and it can't be recovered. You then have a seemingly valid URL that inexplicably doesn't work. Spare yourself the trouble :)
Upvotes: 0
Reputation: 35011
http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-
Given that the javadocs say exactly the same thing for both methods, I'd assume there are no benefits
Upvotes: 0
Reputation: 72844
Both are pretty much the same except for the return object. getResourceAsStream
eventually calls getResource
and returns an opened InputStream
from the URL
object as shown in the following snippet from the ClassLoader
class:
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
Upvotes: 1