Dynamically load images inside jar

Posted by Rahat Ahmed on Game Development See other posts from Game Development or by Rahat Ahmed
Published on 2012-06-11T02:06:23Z Indexed on 2012/06/11 4:47 UTC
Read the original article Hit count: 279

Filed under:
|
|
|

I'm using Slick2d for a game, and while it runs fine in Eclipse, i'm trying to figure out how to make it work when exported to a runnable .jar. I have it set up to where I load every image located in the res/ directory. Here's the code

/**
 * Loads all .png images located in source folders.
 * @throws SlickException
 */
public static void init() throws SlickException {

    loadedImages = new HashMap<>();
    try
    {
        URI uri = new URI(ResourceLoader.getResource("res").toString());
        File[] files = new File(uri).listFiles(new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name)
            {
                if(name.endsWith(".png"))
                    return true;
                return false;
            }

        });

        System.out.println("Naming filenames now.");

        for(File f:files)
        {
            System.out.println(f.getName());
            FileInputStream fis = new FileInputStream(f);
            Image image = new Image(fis, f.getName(), false);
            loadedImages.put(f.getName(), image);
        }
    } catch (URISyntaxException | FileNotFoundException e)
    {
        System.err.println("UNABLE TO LOAD IMAGES FROM RES FOLDER!");
        e.printStackTrace();
    }

    font = new AngelCodeFont("res/bitmapfont.fnt",Art.get("bitmapfont.png"));

}

Now the obvious problem is the line URI uri = new URI(ResourceLoader.getResource("res").toString()); If I pack the res folder into the .jar there will not be a res folder on the filesystem. How can I iterate through all the images in the compiled .jar itself, or what is a better system to automatically load all images?

© Game Development or respective owner

Related posts about java

Related posts about image