0

I am trying to load files from my resource folder using the following code:

URL res = getClass().getClassLoader().getResource("test/test.txt");
File file = new File(res.toURI());
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());
br.close();

This works fine in Eclipse, but when I export it to an executable .jar file and run it (using java -jar), I get the following error:

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:61)
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
        at java.io.File.<init>(Unknown Source)
        at Run.run(Run.java:34)
        at Run.main(Run.java:7)
        ... 5 more

I don't understand why this is happening, since when I open my .jar file with WinRar, the files I am trying to read are in fact there.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Does this answer your question? [Why is my URI not hierarchical?](https://stackoverflow.com/questions/18055189/why-is-my-uri-not-hierarchical) – Shane Creedon Mar 29 '20 at 12:47
  • *"test/test.txt"* Would have the method presuming the resource is in a path relative to the package of the class invoking it. To have the resource search from the root of the path, make it with a leading `/` vis `"/test/test.txt"` **Edit.** `org.eclipse.jdt.internal.jarinjarloader` Wait .. *what?* Simplify the matter by either extracting the resources from each jar and making a new one containing all resources, or include a class-path in the main Jar that lists to other Jars. (Is what I'd recommend, before wondering why it fails.) – Andrew Thompson Mar 29 '20 at 12:49

0 Answers0