【问题标题】:.getResource could not find the file in the resouce folder.getResource 在资源文件夹中找不到文件
【发布时间】:2018-09-09 11:28:13
【问题描述】:

这可能被问了很多,但由于某种原因,我的 getResource 方法无法在我的资源文件夹中找到该文件。该文件位于programfolder/resources/images/drag.png。我的 getResource 代码是:

SidebarItem.bufferedImage = ImageIO.read(Main.class.getResource("/images/drag.png"));

我的类路径是:

<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="resources"/>

每当我运行主类时,它总是抛出异常,因为它可以找到drag.png 文件。谢谢

【问题讨论】:

  • 可能相关:Loading image resource
  • 你的课程是如何运作的?
  • 我只是通过我的 IDE 运行它。我应该创建一个可执行的 jar 来代替吗?
  • 尝试 Main.class.getResource("images/drag.png") 开头不带斜线
  • 我尝试删除图像前的斜线,但由于某种原因它仍然不起作用

标签: java getresource


【解决方案1】:

尝试使用此代码:

ClassLoader cl = Main.class.getClassLoader();
SidebarItem.bufferedImage = ImageIO.read(cl.getResourceAsStream("images/drag.png"));

【讨论】:

  • 仍然不起作用.. 但理论上,鉴于我的文件的位置和我的代码,它应该可以正常工作吗?
  • 是的,应该。我唯一能看出错误的是/images/drag.png
  • 你不需要在图片前加上'/'。
猜你喜欢
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2017-08-13
  • 2016-08-12
  • 2020-03-08
  • 1970-01-01
  • 2019-10-23
  • 1970-01-01
相关资源
最近更新 更多