【问题标题】:get path of image file that is outside the project in java在java中获取项目外部的图像文件的路径
【发布时间】:2011-12-22 00:04:15
【问题描述】:

我使用此代码显示位于我的 java 项目之外的图像,但我每次都得到 NullPointerException,我只能使用我的项目目录内的图像。为什么?

Icon welcomeImg = new ImageIcon(getClass().getResource("D:/img/welcome.png"));
or 
Icon welcomeImg = new ImageIcon(getClass().getResource("D://img/welcome.png"));

JLabel welcomingLb = new JLabel(welcomeImg);

【问题讨论】:

  • welcome.png 听起来像一个应用程序资源,可能是一个闪屏。是吗?如果是这样,使用File 对象的建议不是要走的路。有关详细信息,请参阅this answer

标签: java image user-interface resources icons


【解决方案1】:

您无需使用ClassLoader 类来访问您的文件,因为您提供了它的完整路径。

试试吧:

Icon welcomeImg = new ImageIcon("D:/img/welcome.png");

来源:ImageIcon(String filename)的Javadoc

【讨论】:

    【解决方案2】:

    getResource 期望资源位于类路径中。

    如果要从随机文件中读取,请使用File,或使用ImageIcon constructor that takes a file name

    【讨论】:

      【解决方案3】:

      见:Loading resources using getClass().getResource()

      基本上,当您使用 getResource 时,它​​期望文件位于 Classpath 上。还有一个 ImageIcon 的构造函数,它接受一个 String 文件名,因此您可以直接将路径传递给 Icon 文件。

      查看JavaDoc for ImageIcon

      【讨论】:

      • 我在工作中坚持使用 Java 1.2,因为我们在 Windows Mobile 上使用的是旧的 JVM,所以 1.4 实际上对我来说是一个进步;)
      • “Google 上的第一个结果” 如果您 add a '7'(通常)则不会。
      【解决方案4】:

      您可以尝试使用文件,如下所示:

      File f = new File("C:\\folder\\stuff\\MyFile.class");
      

      【讨论】:

      • 啊,感谢您的澄清。已经有一段时间。编辑反映。
      • 好吧,那更糟,因为那些是反斜杠,需要转义。
      猜你喜欢
      • 2015-11-07
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多