Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Setting image path correctly under a JAR file

pianomarpianomar Kuala LumpurMember Posts: 1

My very first question.
I created a simple slideshow desktop java program that works perfectly when I run it in the NetBeans environment.
However, after building it, and accessing the jar file using "java -jar", it shows an error.
MY QUESTION: Why is this error showing although the file heirarchy and the path specified are matching?

ERROR:

Method showing error:

public void showImage(int index) throws IOException{
        String[] imagesList = getImages();
        String imageName = imagesList[index];
ImageIcon icon= new  ImageIcon(ImageIO.read(getClass().getResourceAsStream("/Images/Images/"+imageName)));
        Image image = icon.getImage().getScaledInstance(ImageHolder.getWidth(),ImageHolder.getHeight(),index);
        ImageHolder.setIcon(new ImageIcon(image));
    }

**Heirarchy: **

What I have tried:

using an input stream like:
InputStream stream = getClass().getClassLoader().getResourceAsStream("Images/Images/"+imageName);
// ImageIcon icon= new ImageIcon(ImageIO.read(stream));

Removing the backslash before Images" in the path

putting the images folder in the same folder as the main class

Editing the manifest file manually

Not using the "File" Object as I realized it doesn't work in a jar file

Tagged:

Comments

  • Nihar MoreNihar More Member Posts: 3

    This is deliberate. The contents of the "file" may not be available as a file. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system.

    Anything you can do by getting a java.io.File could be done by copying the stream out into a temporary file and doing the same, if a java.io.File is absolutely necessary.

    Learn Java https://hackr.io/tutorials/learn-java

  • Sam BerrySam Berry Member Posts: 2

    Thanks @Nihar for this link.


    Get Assignment help.

Sign In or Register to comment.