简体   繁体   中英

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?

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");

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 ;).

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