Keno
Keno

Reputation: 2098

Exported Jar file won't read file inside jar

In the code sample below, when I test the code in Eclipse it works just fine. However, when I export the jar file and test it via the command line, it throws an error: IIOException: Can't read input file!

private BufferedImage img = null;
private String imgSource;

if (img == null)
{
    try {
        URL url = getClass().getResource("Images/questionMark.png");
        System.out.println(url.getPath()); 
        /* This prints: file:/C:/Users/Keno/Documents/javaFile.jar!/javaFile/Images/questionMark.png */
        File file = new File(url.getPath());
        img = ImageIO.read(file);
        imgSource = file.getName();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The file I want to get is located inside the Images folder which is inside the javaFile package. I've noticed one thing that may indicate the problem.

  1. In the print statement I have, I notice an exclamation sign at the end of the javaFile.jar section. Is that correct? Could that indicate an issue with the file or structure?

Also, just in case someone has a better suggestion as to how I should load the file, I'll tell you my intentions. I would like to load the file from a relative location (Images folder) in the jar. I would like to display it (Already done in my actual code) and also store the location to be passed later on to another function (also done).

Upvotes: 0

Views: 892

Answers (2)

Olivier Boissé
Olivier Boissé

Reputation: 18113

try this

public void test() {
    try(InputStream is = getClass().getResourceAsStream("Images/questionMark.png")) {
        ImageIO.read(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 1

Webster
Webster

Reputation: 164

You should try to check if your class is in the same directory than Images inside your jar.

   |
   |- Your class
   |- Images
       |- questionMark.png

Also, have you tried using directly your url object ?

File file = new File(url);

Upvotes: 0

Related Questions