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
Get a resource using getResource()
提问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 static
method, 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文件。
我在这里留下了更详细的答案... 资源实际位于何处