WSK
WSK

Reputation: 6198

How to resolve path of a static file in Java?

How can I find path of a xml (static myXml.xml) file that is embedded into jar? Obviously not by absolute path but I am facing same kind of problem with relative paths. I cannot get it relative to home folder as Java returns different home folder depending upon from where I am calling the accessing Java class. For instance, from:

Is there someway that my accessing class (packed in same jar) may access embedded xml regardless of where jar file exists and who is trying to access it?

Upvotes: 4

Views: 2710

Answers (3)

Vladimir
Vladimir

Reputation: 10513

You can use ClassLoader#getResource(..) to get InputStream of a file from the classpath:

Object.class.getClassLoader().getResource().openStream()

Also there are some other methods in ClassLoader which could be useful in your case.

Upvotes: 0

jjnguy
jjnguy

Reputation: 138942

What you need to do is use the class loader to load the file:

InputStream stream = this.getClass().getClassLoader().
                                              getResourceAsStream("myXml.xml");

The above code assumes that the file is at the top level of your jar.

Upvotes: 6

javamonkey79
javamonkey79

Reputation: 17775

Have you tried the getResource and getResourceAsStream methods in the Class class? Usually those are what I have to resort to in these situations.

Hope this helps.

Upvotes: 0

Related Questions