Avery246813579
Avery246813579

Reputation: 309

Can't read input file when compressed as a jar

I am trying to run a jar file in terminal when I get this error:

enter image description here

I can run this file fine in my IDE, but when I export the project as a jar, it cannot find the file. Here is the code that the error points to:

BufferedImage buttonIcon = ImageIO.read(new File("img/button.png"));
button = new JButton(new ImageIcon(buttonIcon));

Upvotes: 1

Views: 2517

Answers (4)

Dustin
Dustin

Reputation: 1

Use the following:

ImageIO.read(getClass().getClassLoader().getResource(path));

make sure the path doesn't contain the src folder (but keep the images in the actual folder)

path = "image.jpg";

Upvotes: 0

Edwin Buck
Edwin Buck

Reputation: 70939

There are two issues.

  1. You need to put the file into the jar.
  2. You need to use getResourceAsStream(...) to use the class loader to load from the jar.

To verify the image presence in the jar file, use the command jar -tf jarfile.jar and see if button.png is in the jar, where it is expected. If it is not, look into altering your jar packaging.

As for the getResourceAsStream(...) there are many who have already offered how to do this properly. Look to their answers.

Upvotes: 2

Deepanshu J bedi
Deepanshu J bedi

Reputation: 1540

If you want to read that file from inside your JAR use:

BufferedImage buttonIcon = ImageIO.read( getClass().getResourceAsStream("/classpath/to/my/file"));

Upvotes: 1

NTK88
NTK88

Reputation: 593

Try this one:

String imgPath = "img/button.png";
BufferedImage buffImage = ImageIO.read(getClass().getResourceAsStream(imgPath));

Upvotes: 1

Related Questions