Get a resource using getResource()

ⅰ亾dé卋堺 提交于 2020-01-18 02:20:05

问题


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?


回答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.



回答2:


Instead of explicitly writing the class name you could use

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



回答3:


if you are calling from static method, use :

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



回答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



来源:https://stackoverflow.com/questions/2593154/get-a-resource-using-getresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!