调试模式下 getClass().getResource(path) 的路径

问题描述 投票:0回答:1

我有这样一段代码

private Image createImage(String path)
{
    URL imageURL = getClass().getResource(path);

    if (imageURL == null)
    {
        System.err.println("Resource not found: " + path);
        return null;
    }
    else
    {
        return (new ImageIcon(imageURL)).getImage();
    }
}

当我使用 jar 文件运行应用程序时,

getResource()
的路径设置为
/data/ico.png
并且因为位于
ico.png
中的 jar
app.jar/data/ico.png
文件内,一切正常并且创建了图像。
然而,当我尝试使用 IDE 调试它时,我将一个参数传递给应用程序
isdebug
,基于我将路径更改为
..\\..\\..\\data\\ico.png
。结果我没找到
ico.png

我可以用这种方式使用
getResource()
还是我只是错过了 png 文件?
或者也许有一些常见且更好的方法来执行诸如 jar/调试模式下的路径之类的事情?
目录结构是

src.packageA.packageB.MainClass.java

并且 ico.png 位于里面

data\ico.png

===解决办法===
我发现我的结构的正确路径是

../../../../data/ico.png
。在此配置中,位于 a.b.gui.MyClass 中的
ico.png
已正确加载。
我还注意到搜索的目录是
MyClass.class.getResource()
而不是
bin
!这是重要的信息,因为在调试模式下启动 Eclipse 根文件夹不是项目文件夹,而是
src
    

java image debugging path jar
1个回答
1
投票
bin

- 不。但是,

..
允许您以斜线开头,这意味着相对于该类路径条目的
root
来查找资源。例如,如果你的罐子中有这样的结构: getResource

(即,这就是您运行 
mypkg/MyClass.class mypkg/icons/icon1.png logos/logo1.png

时看到的内容),然后您就可以访问所有这些:

jar tvf myjar.jar

一些注意事项:

    MyClass.class.getResource("icons/icon1.png"); MyClass.class.getResource("/mypkg/icons/icon1.png"); MyClass.class.getResource("/mypkg/logos/logo1.png");
  • 错了。
    getClass().getResource()
    是正确的。当你子类化时,
    MyClass.class.getResource()
    会中断。即使
    不这样做,编写脆弱的代码也不好。 这里永远不要使用反斜杠。这是 Windows 的事情,因此无关紧要 - (即使您在 Windows 上运行 Java 应用程序,您也会使用正斜杠。您传递给 getResource 的东西是资源标识符,而不是路径。这与
  • getClass()
  • 不是相同的原因好吧)。
    
        
© www.soinside.com 2019 - 2024. All rights reserved.