Mordecai
Mordecai

Reputation: 49

In java, how do you retrieve images from a jar file?

I've been having problems exporting my java project to a jar (from Eclipse). There is a file that I've included in the jar named images. It contains all of the image files used by my project. The problem is, my references to those images only work when the project isn't in jar form. I can't figure out why and I'm wondering if I need to change the wording of the image references. This is what I'm doing to reference images:

    URL treeURL = null;
    Image tree = null;
    File pathToTheTree = new File("images/tree.png");
    try {
        treeURL = pathToTheTree.toURL();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        tree = ImageIO.read(treeURL);
    } catch(IOException e) {
        e.printStackTrace();
    }

Most likely it is a simple problem, as I'm a beginner at coding. What do I need to change to make these references work when it's all in a jar?

Upvotes: 2

Views: 2861

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

It is indeed simple: you use the various getResource() methods in java.lang.Class and java.lang.ClassLoader. For example, in your app, you could just write

treeURL = getClass().getResource("/images/tree.png");

This would find the file in an images directory at the root of the jar file. The nice thing about the getResource() methods is that they work whether the files are in a jar or not -- if the images directory is a real directory on disk, this will still work (as long as the parent of images is part of your class path.)

Upvotes: 5

Related Questions