Why should I use getResource()?

Asked

Viewed 2,408 times

4

In Java it is nothing unusual to see codes that carry images, audio files, XML and other things like this:

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

However, by the codes I’ve been reading and by 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 reach 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", as it is what I see in applications and libraries "famous".

But I don’t understand why getResource is more used. What advantages does it offer? Because, in general, I should use getResource()?

  • 3

    getClass().getClassLoader().getResource("icon.png") or getClass().getResource("icon.png") will basically search for the resource even when your application is already packaged... new ImageIcon("res" + System.getProperty("file.separator") + "icon.png") will not find your "icon.png" file, unless it has been deleted from Packaging and added in the same folder as your .jar.

  • 2

    @Josue, wouldn’t it be nice to turn that comment into a response? Why, until 19 hours after publication, is the only available and explanatory answer to the question.

1 answer

6


In short:

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

will basically search for the resource 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 deleted from 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 question of getting "more professional" but the correct form.

For a more detailed answer about this, follow the source:

Soen

  • 1

    Upvoted and selected as the best answer because it is the only one. And, stopping to think, this is obvious: Resources are together with the . jar.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.