3 votes

URI is not hierarchical (JAVA)

I am having a rather uncomfortable problem. I generated a test JAR executable file, and it is generating the following error:

Exception en thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: URI is not hierarchical
    at java.io.File.<init>(Unknown Source)
    at Trivia.Interfaz.<init>(Interfaz.java:74)  <= mi codigo

introducir la descripción de la imagen aquí

Starting with the internal scheme of my project. I have the program images saved as separate packages.

introducir la descripción de la imagen aquí

The package where I have the images is called "assets".

Well, in the code when I load the images I have it written as follows:

Image img = ImageIO.read(new File(getClass().getResource("/assets/panama-16.png").toURI()));

Doing it this way, it does not give any kind of error and the program runs normally in the netbeans IDE, but the problem starts when I generate the JAR executable. And I read somewhere that this is caused by the reason that at the time of generating the executable, Netbeans what it does is to compress all those files (ZIP), and of course, already with that things change drastically in terms of the use of the URL.

My question is: How can I make from the JAR file to run normally all those images inside some package of the project without any problem?


SJuan76 Points 7859

The problem is that getResource the returns a URL. When the URL points to a file on the file system, there is no problem in creating a File with them, but if it is a resource inside a jar then it is not appropriate to open it as a File .

My favorite is to always use Class.getResourceAsStream(String) which returns a InputStream from where you can obtain the resource.

Like ImageIO.read has an overload that accepts a InputStream do:

Image img = ImageIO.read(getClass().getResourceAsStream("/assets/panama-16.png"));


Stefan Nolde Points 6308

Within the .jar you can't use File . Use ImageIO.read(InputStream io) instead.

Image img = ImageIO.read(getClass().getResourceAsStream( "/assets/panama-16.png" ));

The reason why a file descriptor cannot be used is that the data within a file can be used as a file descriptor. .jar in fact they are not files. Note that the path inside the .jar has to be from the root of the jar, so start with / .


Luis Points 41

I use these two for images that are in the jar:

Image imga = new ImageIcon(getClass().getResource("/res/img/imagen.jpg")).getImage();

ImageIcon img=new ImageIcon(NombreClase.class.getResource("/res/img/imagen.jpg"));


HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: