java – Why should I use getResource()?

Question:

In Java it's not uncommon to see code that loads images, audio files, XML and other things like this:

final ImageIcon programLogo = new ImageIcon("res" + System.getProperty("file.separator") + "icon.png");

However, from the code I've been reading and from what I've been seeing in the new Java libraries, a more experienced programmer would do this:

final ImageIcon programLogo = new ImageIcon(getClass().getResource("res/icon.png"));

The two ways don't achieve the same result: The root path of the first example starts from the root path of ClassLoader and the root path of the second starts from the parent folder of .class, but the second seems to be more "professional", since that's what I see it in "famous" applications and libraries.

But I don't understand why getResource is used the most. What advantages does it offer? Why in general should I use getResource()?

Answer:

In summary:

getClass().getClassLoader().getResource("icon.png") 
//ou 
getClass().getResource("icon.png")

they will basically look for the resource even when your application is already packaged. Although:

new ImageIcon("res" + System.getProperty("file.separator") + "icon.png")

It won't find your "icon.png" file unless it has been excluded from the packaging and added to the same folder as your .jar

This is a very common mistake for those who are going to distribute the jar for the first time, it is not a question of getting "more professional" but the correct way.

For a more detailed answer, the source follows:

SOen

Scroll to Top