0

So I'm using an image for the chess pieces in this basic chess game I'm making.

When I run the program in Eclipse, it works perfectly fine as expected. But when I use Eclipse to export and then run that program, it gives the error java.imageio.IIOException: Can't read input file!

The image is stored in the source folder in a package names images.

I load the image using

BufferedImage image = null;

try {
    image = ImageIO.read(new File("src/images/Chess_Pieces.png"));
} catch (IOException e) {
    System.out.println(e);
}

I've tried locating the image to many different places and I've tried different ways of loading the image, none of them work and I have made sure that the image actually appears correctly in the exported JAR file.

  • 1
    See https://stackoverflow.com/questions/30282834/loading-resource-files-within-a-jar – Markaos Jul 31 '20 at 06:25
  • 1
    two possible solutions: distribute the images separately from the jar or pack them into the jar as resources and read them in the program as resources instead of from file. – Henry Jul 31 '20 at 06:25
  • 3
    Does this answer your question? [Jar get image as resource](https://stackoverflow.com/questions/10163012/jar-get-image-as-resource) – T A Jul 31 '20 at 06:32

1 Answers1

0

Change it:

image = ImageIO.read(getClass().getResource("/images/Chess_Pieces.png"));

See :

  • Thank you so much, this fixed the problem. I'm quite new to Java, could I ask what's the difference between this and what I was previously doing.? – silvershark3 Jul 31 '20 at 07:01
  • When you build a jar. The file is no longer in the src directory. It will be packaged with the class file. So when you run jar, it can not find them. getResource() return the URL object to load resources from jar – Lê Hoàng Dững Jul 31 '20 at 07:08
  • Ok, thank you very much, I'll keep that in mind. – silvershark3 Jul 31 '20 at 07:13