Use class.getResource () to load a file inside .jar?

I have the following directory structure in my java project:

enter image description here

This project is managed Maven, and when the package of all resources is placed in one file .jar.
In Utils.javaI load car.jpg, and since the texture file is in the classpath, I use the following method to get the file descriptor:

URL url = Utils.class.getResource("/textures/car.jpg");

I saw a lot of confusion as to which method to use when getting a file reference in the classpath.
Is the class.getResource()right method? Or class.getResourceAsStream()offers any benefits?

+4
source share
3 answers

, . getResourceAsStream getResource InputStream URL, ClassLoader:

public InputStream getResourceAsStream(String name) {
    URL url = getResource(name);
    try {
        return url != null ? url.openStream() : null;
    } catch (IOException e) {
        return null;
    }
}
+1

getResource(), . getResourceAsStream(), .

, URL (URL.toString()) , URL-.

, , URL , , . URL . URL-, ClassLoader; ClassLoader URL-, :

 new URL(URL context, String spec, URLStreamHandler handler)

ClassLoader URLStreamHandler. , URL- - String . , -, URL-, . :)

0

All Articles