0

I've made a game that uses images from another file. I asked this question: How can I get a program that uses external files into a JAR? which was marked as duplicate. The other question seemed to only deal with text files, and didn't help at all. I did a bit more research, and I think I need to put the project and the image files into one jar. I looked at this question: How can I include my icon when I export my project to a jar file, but I couldn't understand how to do it by reading the answer. I would have commented to ask for more clarity, but I need 50 reputation, which I don't have yet. I just need my program to be able to use image files when it is in jar form. It seems strange that things that work in an IDE don't always work in a jar. :P

This is the method I'm using to get the image files:

private Image retrieveImage(String filePath)
{
    try{
        Image image = (Image)ImageIO.read(new File(filePath));
        return image;
    } catch(Exception exc)
    {
        System.out.println(exc.toString());
        return null;
    }
}

The exception I get is: javax.imageio.IIOException: Can't read input file!

Thanks for all your help :)

Community
  • 1
  • 1
Bom Tomdabil
  • 61
  • 1
  • 10
  • 1
    You cannot access a resource within a JAR file as a `File`. `new File(filePath)` won't work. You have to use an `InputStream` to read its content, with [`ImageIO.read(InputStream)`](https://docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html#read-java.io.InputStream-). Refer to the linked question. – Tunaki Jun 12 '16 at 17:06
  • @Tunaki I tried this: `InputStream in = getClass().getResourceAsStream(filePath); Image image = (Image)ImageIO.read(in);`, but image comes out as null. – Bom Tomdabil Jun 12 '16 at 21:06
  • Well actually, I get this: `java.lang.IllegalArgumentException: input == null!`, but image being null is the only explanation I can see for that – Bom Tomdabil Jun 12 '16 at 21:11
  • Then it means that the image wasn't found at `filePath`. The path given to `getResourceAsStream` is absolute, starting at the root of the JAR. If the resource is at the root, then you should have `getResourceAsStream("/myImage.png")`. – Tunaki Jun 12 '16 at 21:24
  • @Tunaki The resource isn't inside the jar. I posted this question to try to find out how to get it there. – Bom Tomdabil Jun 14 '16 at 03:31

0 Answers0