Search code examples
javaswingembedded-resourceimageiconjavax.imageio

javax.imageio.IIOException When reading the Input File


I am trying to set Image to a JLabel. I used this code, And it works fine in the IDE. But when I try to run Executable Jar file in dist folder It gives me this error.

javax.imageio.IIOException: Can't read input file!

How to fix that issue. Please anyone can help me? Thanks in advance.

Code is,

ImageIcon iconPicture = new ImageIcon(ImageIO.read(new File("./src/PIC/Images/profileImage.png")));
pictureLabel.setIcon(iconPicture);

Solution

  • You can't rely on the "working directory" been the same as the location where the Jar/classes are stored.

    ImageIcon iconPicture = new ImageIcon(ImageIO.read(new File("./src/PIC/Images/profileImage.png")));
    

    This suggests to me that you are dealing with an embedded resource, one which is contained within the classpath/Jar file. In this case, you should be loading the resource using Class#getResource instead, as the resource won't be readable as a File (if it's contained in the Jar file).

    So, instead of the above, you should be doing something more like...

    ImageIcon iconPicture = new ImageIcon(ImageIO.read(getClass().getResource("/PIC/Images/profileImage.png")));