Java从jar加载文件

时间:2017-07-03 16:09:44

标签: java file jar resources load

我不知道如何从制作的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的结构是:

  • META-INF
  • de(以及包含类文件的其余包)
  • 文件1
  • file2的
  • ......等等

所以这些文件直接放在jar中,不在任何子文件夹中。

1 个答案:

答案 0 :(得分:1)

您的代码不起作用,因为File对象不能用于访问jar中的文件。你可以做的是使用ZipInputStreams打开&与ZipEntry一起阅读你的jar文件,阅读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);
        // ...
    }
}

使用已设置的网址,我们可以使用以下简单代码确定程序是否在jar中:

new File(jar.getFile()).toString().endsWith("jar")
这是有效的,因为在IDE中,(在我的情况下是eclipse) new File(jar.getFile()).toString()返回 "D:\Java\Current%20Projects\Test\bin" 在罐子里,我得到了 "D:\Windows%20Folders\Desktop\Test.jar"