expensne
expensne

Reputation: 29

Java loading files from the jar

I don't get how to load files from the produced Jar.

This is my code and it works fine inside the IDE, but not when I run the 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();
    }

The structure of the Jar is:

So the files are directly in the jar not in any subfolder.

Upvotes: 1

Views: 160

Answers (1)

Troy Neubauer
Troy Neubauer

Reputation: 126

Your code doesn't work because File objects cannot be used to access files inside a jar. What you can do is use ZipInputStreams to open & read your jar file alongside ZipEntry's to read the individual files in your jar. This code will work in a jar, but most likely not in an IDE. In which case, you can detect the current state (IDE or Jar) and execute the desired loading code accordingly.

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);
        // ...
    }
}

Using the URL's already setup, we can determine if the program is in a jar or not with this simple code:

new File(jar.getFile()).toString().endsWith("jar")
This works because when in an IDE, (eclipse in my case) new File(jar.getFile()).toString() returns "D:\Java\Current%20Projects\Test\bin" where as in a jar, I got "D:\Windows%20Folders\Desktop\Test.jar"

Upvotes: 1

Related Questions