URI is not hierarchical (JAVA)


I'm having a very uncomfortable problem. Generate 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

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

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

Well, in the code when I upload 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 type of error and the program runs normally in the IDE of netbeans, but the problem starts when I generate the executable JAR. And I read that this is caused by the reason that when generating the executable, Netbeans what it does is 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 all these images normally inside some package of the project without any problem?

asked by TwoDent 27.01.2017 в 20:37

3 answers


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

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

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

Image img = ImageIO.read(getClass().getResourceAsStream("/assets/panama-16.png"));
answered by 27.01.2017 / 20:52

Within .jar you can not use File . Use ImageIO.read (InputStream io) instead.

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

The reason why you can not use a file descriptor is that the data inside a .jar is in fact not files. Mind you, the path inside .jar has to be from the root of the jar, so start with / .

answered by 27.01.2017 в 20:51

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"));
answered by 31.07.2017 в 06:34