20

I need to package a configuration file within a jar. the configuration file is under the root of the jar file. However I got the following error:

Caused by: java.lang.IllegalArgumentException: URI is not hierarchical at java.io.File.(Unknown Source)

File url = new File(MyClass.class.getClassLoader().getResource("my.conf").toURI());
mattbasta
  • 13,492
  • 9
  • 47
  • 68
user217631
  • 1,278
  • 5
  • 18
  • 33

3 Answers3

29

You should use getResourceAsStream() instead. If the file is embedded in your JAR the URI is most likely bundle:// URI

InputStream is = this.getClass().getResourceAsStream("my.conf");
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Andrew T Finnell
  • 13,417
  • 3
  • 33
  • 49
7

Why do you need a file? IF you need to read the config use

Class.getResourceAsStream("/my.conf");

This will need only to be the file in the one folder with the root of your package( the same as in the root of the jar)

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
4

The file should be in the same package as the MyClass. I just realized you are creating a File object. Instead try using getResourceAsStream(). This is the right way if you want to read the contents from a classpath resource. Here is the example.

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
  • correction: the file was found, but since it's inside a jar, i got uri is not hierarchical error – user217631 Dec 28 '10 at 19:18
  • Following error should be shown "Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical" – hiropon Oct 02 '17 at 07:36