指定可执行 jar 中子目录的文件路径

Specifying filepaths to subdirectories inside executable jar

我正在开发一个 java 项目并将其制作成可执行的 jar。在 jar 中,包含了所有正确的文件,但是当 运行打开 jar 时,图像不显示。

当我从命令行运行程序时,程序能够正确显示所有内容。

我认为问题可能出在我如何在代码中设置文件路径? 这是我的设置示例:

private static String imgPath;
...
    imgPath = String.format("img%d.gif", value);
...
public static ImageIcon getImageIcon() {
    ImageIcon ii = new ImageIcon("content/dice/" + imgPath);
    return ii;
}
//getImageIcon() is later called by another class

除非我尝试从可执行 jar 中 运行 程序,否则此设置有效。所以我的问题是如何让它在罐子里工作?

第一个错误是假设 Jar 中有一个文件系统(目录等)。有些资源路径可能看起来像目录和文件,但没有目录或文件本身。

应用程序资源在部署时将成为嵌入式资源,因此明智的做法是立即开始访问它们。关于如何形成 URL.

must be accessed by URL rather than file. See the info. page for embedded resource