Reputation: 309
I am trying to run a jar file in terminal when I get this error:
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
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
Reputation: 70939
There are two issues.
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
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
Reputation: 593
Try this one:
String imgPath = "img/button.png";
BufferedImage buffImage = ImageIO.read(getClass().getResourceAsStream(imgPath));
Upvotes: 1