user217631
user217631

Reputation: 1308

load file within a jar

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());

Upvotes: 20

Views: 33744

Answers (3)

Andrew T Finnell
Andrew T Finnell

Reputation: 13638

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");

Upvotes: 29

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

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)

Upvotes: 7

Aravind Yarram
Aravind Yarram

Reputation: 80194

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.

Upvotes: 4

Related Questions