简体   繁体   中英

Use class.getResource() to load file within .jar?

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?

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;
    }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM