75

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?

MxNx
  • 1,342
  • 17
  • 28
lbedogni
  • 7,917
  • 8
  • 30
  • 51

4 Answers4

126
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.
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 7
    Just be aware that `Class#getResource` and `ClassLoader#getResource` are using different strategies to map the name to a location. LucaB's example actually uses the ClassLoader from Class (`SomeClass.class.getClass()`), but that's probably a mistake and not on purpose. – jarnbjo Apr 07 '10 at 14:45
  • @jambjo yes, I assumed it's a mistake. – Bozho Apr 07 '10 at 14:46
  • 1
    It is a mistake. Thanks for the hint – lbedogni Apr 07 '10 at 20:55
  • I tested it but this returned null. I wrote like that: `MyClass.class.getResource("/WebContent/WEB-INF/xsd/MyXsd.xsd")`. any mistake I did? – kamal Jun 07 '13 at 06:34
23

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");
arush436
  • 1,748
  • 20
  • 20
10

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");
fabian
  • 80,457
  • 12
  • 86
  • 114
Binoy Babu
  • 167
  • 2
  • 4
3

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

Community
  • 1
  • 1
J.E.Tkaczyk
  • 557
  • 1
  • 8
  • 19
  • 1
    The `.class` file is not necessarily stored in the file system directly. It may also be part of a `.jar` file... – fabian May 07 '18 at 11:55
  • I remarked that `TestGameTable.class.getClassLoader().getResource("dice.jpg");` worked in packaged App/jar but `getClass().getResource("/unibo/lsb/res/dice.jpg");` didn't work. – Jaja Feb 22 '21 at 09:12