I'm having a pretty awkward problem. I generated a test executable JAR 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 schematic of my project. I have the images of the program saved as separate packages.
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 doesn't 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 when generating the executable, what Netbeans does is compress all those files (ZIP), and of course, with that things change drastically in terms of the use of the URL .
My question is: How can I make all those images run normally from the JAR file inside a project package without any problem?
The problem is that
getResource
the returns a URL. When the URL points to a file on the file system, there is no problem creating aFile
with them, but if it is a resource inside a jar then it is not appropriate to open it asFile
.My favorite is to use always
Class.getResourceAsStream(String)
, which returns aInputStream
where you can get the resource from.Since
ImageIO.read
it has an overload that accepts aInputStream
, do:Inside the .jar you cannot use
File
. Use ImageIO.read(InputStream io) instead.The reason you can't use a file descriptor is that the data inside a .jar is not actually a file. Be careful , the path inside the .jar has to be from the root of the jar, so start with
/
.I use these two for images that are in the jar: