Java 从 .jar 文件加载图像

Java Image Loading from .jar File

我正在尝试从用户放置图像的名为 Custom 的文件夹中加载图像。这是我用来加载图像的方法:

public BufferedImage getCustImg(String path){
    BufferedImage img = null;
    String s = get.getProgramPath();
    path = path.trim();
    String s2 = s + "\Custom\" + path + ".png";

    try{
        img = ImageIO.read(this.getClass().getResource(s2));//gets image from file path
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}

这里是程序路径方法

public String getProgramPath(){
    File f = new File("./Resources/Sprtes/blank.png");
    String s = f.getAbsolutePath();
    String[] stringArr = s.split("Resources");
    String s2 = stringArr[0];
    s2 = s2.substring(0, s2.length() - 3);
    return s2;
}

当我 运行 代码时一切正常,但是当我尝试 运行 将程序作为 .jar 文件时出现问题。当我 运行 它使用 .jar 文件时,图像不会加载。这是自定义文件夹与 .jar 文件相关的位置:

File Structure

我应该如何更改方法以确保它有效?

感谢 Luke Lee 和 Olithegoalie,我解决了这个问题,

img = ImageIO.read(this.getClass().getResource(s2)); 如果路径超出 jar 则不起作用,所以我不得不将其更改为

public BufferedImage getCustImg(String path){
    BufferedImage img = null;
    String s = get.getProgramPath();
    path = path.trim();
    String s2 = s + "\Custom\" + path + ".png";
    try{
        img = ImageIO.read(new File(s2));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}