Get a resource using getResource()

JavaResourcesGetresource

Java Problem Overview


I need to get a resource image file in a java project. What I'm doing is:

URL url = TestGameTable.class.getClass().
          getClassLoader().getResource("unibo.lsb.res/dice.jpg");

The directory structure is the following:

unibo/
  lsb/
    res/
      dice.jpg
    test/
    ..../ /* other packages */

The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue. Any hint?

Java Solutions


Solution 1 - Java

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

Solution 2 - Java

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");

Solution 3 - Java

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

Solution 4 - Java

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlbedogniView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - Javaarush436View Answer on Stackoverflow
Solution 3 - JavaBinoy BabuView Answer on Stackoverflow
Solution 4 - JavaJ.E.TkaczykView Answer on Stackoverflow