Posted By: Anonymous
I would like to read a resource from within my jar like so:
File file; file = new File(getClass().getResource("/file.txt").toURI()); BufferedReader reader = new BufferedReader(new FileReader(file)); //Read the file
and it works fine when running it in Eclipse, but if I export it to a jar, and then run it, there is an IllegalArgumentException:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: URI is not hierarchical
and I really don’t know why but with some testing I found if I change
file = new File(getClass().getResource("/file.txt").toURI());
file = new File(getClass().getResource("/folder/file.txt").toURI());
then it works the opposite (it works in jar but not eclipse).
I’m using Eclipse and the folder with my file is in a class folder.
InputStream in = getClass().getResourceAsStream("/file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
As long as the
file.txt resource is available on the classpath then this approach will work the same way regardless of whether the
file.txt resource is in a
classes/ directory or inside a
URI is not hierarchical occurs because the URI for a resource within a jar file is going to look something like this:
file:/example.jar!/file.txt. You cannot read the entries within a
zip file) like it was a plain old File.
This is explained well by the answers to:
- How do I read a resource file from a Java jar file?
- Java Jar file: use resource errors: URI is not hierarchical