Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path for retrieving resources with ClassLoader

Basically, I want to include my main JFrame's icon in the JAR file, so not to need to load it from an external location.

To achieve this, I searched about Java's resource system. What I have done with Eclipse:

  1. I have created a new folder named "res":

  2. I have copied the files inside it using Windows' explorer:

  3. I have made that folder a source folder:

  4. I have written this code:

    URL url = ClassLoader.getSystemResource("/res/icona20.ico");
    

But url is null. What did I do wrong?

like image 983
Atom 12 Avatar asked Aug 31 '15 14:08

Atom 12


People also ask

How do I get the path of a jar file?

getLocation() method gives us the URL object of the JAR file. Finally, we can use the Paths class to get the full path of the JAR file.

How do you find the absolute path to a file in the resources folder of your project?

The function getAbsolutePath() will return the absolute (complete) path from the root directories. If the file object is created with an absolute path then getPath() and getAbsolutePath() will give the same results.

Which ClassLoader loads the files from JDK directory?

Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.

When using class getResourceAsStream Where will the resource be searched?

The getResourceAsStream() method of java. lang. Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of InputStream object.


2 Answers

As mentioned you seem to have added res as source folder, so it is a root, not to name, like src.

URL url = ClassLoader.getSystemResource("icona20.ico");

Class loaders use an absolute (case-sensitive) path, without explicit leading slash /....

Relative paths with an obligatory leading slash for absolute paths:

URL url = Xyz.class.getResource("/icona20.ico");

And you might prefer .png instead of .ico as the latter format is not standard in Java SE.

(About common practices.) The build tool maven uses as nice standard the following source folders:

/src/main/java/
/src/main/resources/
/src/test/java/
/src/test/resources/

Your usage of res is reminiscent of MS Visual Studio ;).

like image 176
Joop Eggen Avatar answered Oct 17 '22 00:10

Joop Eggen


The classloader will get the resources starting from each source folder you added to the classpath. Therefore, the URL should be the following:

URL url = ClassLoader.getSystemResource("icona20.ico");
like image 32
Andres Avatar answered Oct 17 '22 00:10

Andres