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:
I have created a new folder named "res":
I have copied the files inside it using Windows' explorer:
I have made that folder a source folder:
I have written this code:
URL url = ClassLoader.getSystemResource("/res/icona20.ico");
But url
is null
.
What did I do wrong?
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.
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.
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.
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.
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 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With