I would like to read a resource from within my jar like so:
File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferredReader 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 the 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());
to
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.
You could also just use java.nio. Here is an example to slurp in text from a file at
resourcePath
in classpath:After a lot of digging around in Java, the only solution that seems to work for me is to manually read the jar file itself unless you're in a development environment(IDE):
Note: The above code only seems to work correctly for jar files if it is in the main class. I'm not sure why.
To access a file in a jar you have two options:
Place the file in directory structure matching your package name (after extracting .jar file, it should be in the same directory as .class file), then access it using
getClass().getResourceAsStream("file.txt")
Place the file at the root (after extracting .jar file, it should be in the root), then access it using
Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt")
The first option may not work when jar is used as a plugin.
If you are using spring, then you can use the the following method to read file from src/main/resources:
Make sure that you work with the correct separator. I replaced all
/
in a relative path with aFile.separator
. This worked fine in the IDE, however did not work in the build JAR.I had this problem before and I made fallback way for loading. Basically first way work within .jar file and second way works within eclipse or other IDE.