grep grep - 7 months ago 359
Java Question

why my URI is not hierarchical?

I have files in resource folder. For example if I need to get file from resource folder , I do like that:

File myFile= new File(MyClass.class.getResource(/myFile.jpg).toURI());
System.out.println(MyClass.class.getResource(/myFile.jpg).getPath());


I've tested and everything works! Everything is Fine!
path is

/D:/java/projects/.../classes/X/Y/Z/myFile.jpg

But, If I create jar file, using , MAVEN.

mvn package


and then start my app

java -jar MyJar.jar


I have that following error:

Exception in thread "Thread-4" java.lang.RuntimeException: ხელმოწერის განხორციელება შეუძლებელია
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:363)


and path of file is

file:/D:/java/projects/.../target/MyJar.jar!/X/Y/Z/myFile.jpg

This exception happens when I try to get file from resource folder. At this line. why? why have that problem in JAR file? what do you think?

I was searching answers , but non of them was working for me.

or is there another way, to get Resource folder path?

Answer

You should be using

getResourceAsStream(...);

when the resource is bundled as a jar/war or any other single file package for that matter.

See the thing is, a jar is a single file (kind of like a zip file) holding lots of files together. From Os's pov, its a single file and if you want to access a part of the file(your image file) you must use it as a stream.

Documentation