Loading Resources in Runnable Jar

So, I have the following code in a method to load all PNG files found in a specific directory as textures.


String files;
File folder = new File(GRAPHICS_FILE_PATH);
File[] listOfFiles = folder.listFiles(); 
			  
for (int i = 0; i < listOfFiles.length; i++) 
{			  
	    if (listOfFiles[i].isFile()) 
	    {
	    	files = listOfFiles[i].getName();
	        if (files.endsWith(".png") || files.endsWith(".PNG"))
	        {			           
	           Texture temp = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(GRAPHICS_FILE_PATH + "/" + files));
	           texture.put(files.substring(0, files.indexOf(".")), temp);
                }
	     }
}

This works great when testing in the IDE, but I want to distribute my final program as a runnable jar. Since there is only a single jar file and not this blown up file structure, the program freaks out saying it can’t find the specified resource.

If I hard code the texture names, slick’s ResourceLoader class works great in a jar or when the file structure exists; where’s the fun in hard-coding all those texture filenames though? This is programming; we want things done automatically! :wink:

My question is: is there a simple way to retrieve all the resources at a specific path in either a jar or file structure? I found this method, but I’m not having much luck implementing it in a way I can just point to “res/graphics”; it seems to depend on the same folder where the provided class exists.

  • Steve

You can use the JarFile class: http://docs.oracle.com/javase/8/docs/api/java/util/jar/JarFile.html

That class has methods that let you iterate over each file in the jar.

I did exactly the thing you want to do in my resource lib.
The trick is to ask the Classloader for all class-path elements (folder like the working-dir and Jar files).
I implemented this search in a little helper class. I have a dependency on Google Guava, but it should be straight forward to factor this out.

with this class you can to the following:


Collection<URL> images = ClasspathHelper.elementsOfFolder("resources/graphics/", "png");

for(URL url: images)
{
    Texture temp = TextureLoader.getTexture("PNG", url.openStream());
    texture.put(url.getFileName(), temp);
}

and you will get all images, independent if they are located in the working-dir or some library Jar.

Wow! That is awesome! I’m going to have to give this a shot; thank you so much! :slight_smile:

  • Steve

Danny, you’re a lifesaver! That worked great!

Now I’m just going to strip out the Guava stuff; very useful tool!

  • Steve