Java 从 jar 加载文件

Java loading files from the jar

我不知道如何从生成的 Jar 中加载文件。

这是我的代码,它在 IDE 中运行良好,但当我 运行 Jar:

   URL url = ClassLoader.getSystemResource(".");
   try
   {
        File dir = new File(url.toURI());
        for (File f : dir.listFiles())
        {
            String fn = f.getName();
            if (fn.endsWith(".png"))
            {
                ImageView iv = new ImageView(fn);
                // ...
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

Jar 的结构是:

所以文件直接在 jar 中而不在任何子文件夹中。

您的代码不起作用,因为 File 对象不能用于访问 jar 中的文件。您可以做的是使用 ZipInputStreams 打开和读取您的 jar 文件以及 ZipEntry 来读取您的 jar 中的各个文件。 此代码可以在 jar 中运行,但很可能不能在 IDE 中运行。在这种情况下,您可以检测当前状态(IDE 或 Jar)并相应地执行所需的加载代码。

CodeSource src = ClientMain.class.getProtectionDomain().getCodeSource();

URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry entry = null;

while ((entry = zip.getNextEntry()) != null) {
    String entryName = entry.getName();
    if (entryName.endsWith(".png")) {
        BufferedImage image = ImageIO.read(zip);
        // ...
    }
}

使用 URL 的已经设置,我们可以用这个简单的代码确定程序是否在 jar 中:

new File(jar.getFile()).toString().endsWith("jar")
这是有效的,因为在 IDE 中(在我的例子中是日食) new File(jar.getFile()).toString() returns "D:\Java\Current%20Projects\Test\bin" 就像在罐子里一样,我得到了 "D:\Windows%20Folders\Desktop\Test.jar"