Get a resource using getResource()
Solution 1
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
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
Solution 3
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
Solution 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
lbedogni
I'm Luca from Reggio Emilia, Italy. I started programming at 8 years old, beginning with QBasic and then moving to Turbo Pascal, C, PHP, Java. Now I work as a freelancer, while finishing my studies at the University of Bologna, where I got a degree in computer science and I'm attending the full-degree course. My interests are in networks.
Updated on July 05, 2022Comments
-
lbedogni almost 2 years
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?
-
jarnbjo about 14 yearsJust be aware that
Class#getResource
andClassLoader#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. -
Bozho about 14 years@jambjo yes, I assumed it's a mistake.
-
lbedogni about 14 yearsIt is a mistake. Thanks for the hint
-
kamal almost 11 yearsI tested it but this returned null. I wrote like that:
MyClass.class.getResource("/WebContent/WEB-INF/xsd/MyXsd.xsd")
. any mistake I did? -
malana almost 9 yearsOr just
getClass()
withoutthis
. -
Enamul Hassan almost 9 yearswhat about if calling other than static method?
-
flungo over 7 yearsThis is assuming you are not within a static context.
-
fabian about 6 yearsThe
.class
file is not necessarily stored in the file system directly. It may also be part of a.jar
file... -
Jaja over 3 yearsI remarked that
TestGameTable.class.getClassLoader().getResource("dice.jpg");
worked in packaged App/jar butgetClass().getResource("/unibo/lsb/res/dice.jpg");
didn't work.