Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a resource using getResource()

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?

like image 506
lbedogni Avatar asked Apr 07 '10 14:04

lbedogni


People also ask

How do you get resources in Java?

Java programs can use two mechanisms to access resources: Applets use Applet. getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet. getAudioClip(url) . Applications use "well known locations" such as System.

What is the use of get resource method?

The Android resource system keeps track of all non-code assets associated with an application. You can use this class to access your application's resources. You can generally acquire the Resources instance associated with your application with getResources() .

How do I view the resources folder in a jar file?

This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .


2 Answers

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.
like image 90
Bozho Avatar answered Sep 21 '22 07:09

Bozho


Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg"); 
like image 35
arush436 Avatar answered Sep 20 '22 07:09

arush436