Get a resource using getResource()

前端 未结 4 716
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 12:37

I need to get a resource image file in a java project. What I\'m doing is:

URL url = TestGameTable.class.getClass().
          getClassLoader().getResource(\         


        
相关标签:
4条回答
  • 2020-11-22 12:46

    Instead of explicitly writing the class name you could use

    this.getClass().getResource("/unibo/lsb/res/dice.jpg");
    
    0 讨论(0)
  • 2020-11-22 13:00
    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.
    0 讨论(0)
  • 2020-11-22 13:08

    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

    0 讨论(0)
  • 2020-11-22 13:12

    if you are calling from static method, use :

    TestGameTable.class.getClassLoader().getResource("dice.jpg");
    
    0 讨论(0)
提交回复
热议问题