Java 使用 getResource() 获取资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2593154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:38:00  来源:igfitidea点击:

Get a resource using getResource()

javaresourcesgetresource

提问by lbedogni

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

我需要在java项目中获取资源图像文件。我正在做的是:

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?

事实是我总是得到,因为文件不存在。我尝试了许多不同的路径,但我无法解决问题。任何提示?

采纳答案by Bozho

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.
  • 前导斜杠表示类路径的根
  • 路径中的斜线而不是点
  • 你可以getResource()直接在课堂上打电话。

回答by arush436

Instead of explicitly writing the class name you could use

您可以使用而不是显式编写类名

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

回答by Binoy Babu

if you are calling from staticmethod, use :

如果您从static方法调用,请使用:

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

回答by J.E.Tkaczyk

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.javafile.
I left a more detailed answer here... where is resource actually located

要记住的一件事是,此处的相关路径是相对于您的类的文件系统位置的路径……在您的情况下为 TestGameTable。。它与 TestGameTable 的位置无关。java文件。
我在这里留下了更详细的答案... 资源实际位于何处