无法在导出的 jar 中 locate/open 图片

Unable to locate/open image inside exported jar

我在 Stack Overflow 上探索了与此问题相关的每一个解决方案,我遇到的解决方案仅在我的 IDE (Eclipse Mars) 中有效,但在导出时它们都失败了。

我有一个图像文件,我只想从导出的 jar 中加载。

从项目布局中可以看出,Images 是直接位于项目文件夹 CooldownTrackerJava 内的文件夹。为了引用它,我尝试了多种方法。

//My class' name is AddItemDialog

//Method 1
String filePath = File.separator + "Images" + File.separator + "questionMark.png";
InputStream inputStream = AddItemDialog.class.getResourceAsStream(filePath);
BufferedImage img = ImageIO.read(inputStream);

我在几个方面尝试了方法 1。我在 filePath 的开头使用和不使用 File.separator 进行了尝试。 我知道前者是指绝对路径,而后者是相对路径。我还尝试将 Images 文件夹移动到我的 class 文件所在的目录中。

当多次导出和测试时,所有这些都失败了 NullPointerException

//Method 2
String saveLocation = File.separator + "Images" + File.separator + "questionMark.png";    
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(saveLocation));

As per this post 我试了上面的方法还是不行

除了本 post 中提到的那些之外,我已经尝试了很多变体,但是当我导出 jar 时,其中 none 已经成功。

我需要将 Images 文件夹添加到我的构建路径吗?我应该将它移动到 src 文件夹吗?我错过了一个明显的步骤吗?所有建议将不胜感激。这里还有导出的 jar 文件的布局。

解决方案分为两部分。首先,我将 Images 文件夹移动到 src 目录中,如下所示。感谢马修。

然后我删除了 File.separator 并将其替换为正斜杠 /。感谢 fge.

Do not use File.separator(). Separators for resource paths on the class path is always /. If you use Windows you will therefore always get the wrong result.

我使用了方法 1 的变体来测试它。不过这两种方法都可以。

String saveLocation = "/Images/questionMark.png";
InputStream inputStream = this.getClass().getResourceAsStream(saveLocation);
try {
    BufferedImage img = ImageIO.read(inputStream);
} catch (IOException e) {
    e.printStackTrace();
}