Get a resource using getResource()
Asked Answered
W

4

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?

Whitherward answered 7/4, 2010 at 14:15 Comment(0)
E
127
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.
Enslave answered 7/4, 2010 at 14:17 Comment(4)
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<java.lang.Class> (SomeClass.class.getClass()), but that's probably a mistake and not on purpose.Ingoing
@jambjo yes, I assumed it's a mistake.Enslave
It is a mistake. Thanks for the hintWhitherward
I tested it but this returned null. I wrote like that: MyClass.class.getResource("/WebContent/WEB-INF/xsd/MyXsd.xsd"). any mistake I did?Korrie
S
24

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");
Sublunary answered 29/4, 2015 at 11:24 Comment(2)
Or just getClass() without this.Decant
This is assuming you are not within a static context.Limen
C
10

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");
Clog answered 19/7, 2015 at 1:17 Comment(1)
what about if calling other than static method?Addiel
G
4

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

Granddaughter answered 21/1, 2017 at 17:0 Comment(2)
The .class file is not necessarily stored in the file system directly. It may also be part of a .jar file...Decongestant
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.Ancestral

© 2022 - 2024 — McMap. All rights reserved.