Why should I use getResource ()?

3

In Java it is not uncommon to see codes that load images, audio files, XML and other things in a more or less 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 forms do not arrive at the same result: The root path of the first example starts from the root path of the ClassLoader and the root path of the second begins with the parent folder of the .class, but the second one seems to be more "professional" since is what I see in "famous" applications and libraries.

But I do not understand why getResource is more used. What advantages does it offer? Why, in general, should I use getResource ()?

    
asked by anonymous 07.09.2014 / 14:09

1 answer

5

In summary:

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

will basically fetch the feature even when your application is already packaged. However:

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

You will not 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 of who will distribute the jar for the first time, it is not a matter of being "more professional" but the correct way.

For a more detailed answer, see the source:

SOen

    
08.09.2014 / 20:11