Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading xml file inside a jar-package

Here's my structure:

  • com/mycompany/ValueReader.class
  • com/mycompany/resources/values.xml

I can read the file in my Eclipse project, but when I export it to a .jar it can never find the values.xml.

I tried using ValueReader.class.getResource() and ValueReader.class.getResourceAsStream() but it doesn't work.

What's the problem here? How do I get a File-object to my values.xml?

B.

like image 426
B. T. Avatar asked Mar 31 '10 12:03

B. T.


2 Answers

You can't get a File for the file because it's in a jar file. But you can get an input stream:

InputStream in = ValueReader.class.getResourceAsStream("resources/values.xml");

getResourceAsStream and getResource convert the package of the class to a file path, then add on the argument. This will give a stream for the file at path /com/mycompany/resources/values.xml.

like image 30
tbodt Avatar answered Oct 06 '22 03:10

tbodt


You can't get a File object (since it's no longer a file once it's in the .jar), but you should be able to get it as a stream via getResourceAsStream(path);, where path is the complete path to your class.

e.g.

/com/mycompany/resources/values.xml
like image 99
Brian Agnew Avatar answered Oct 06 '22 04:10

Brian Agnew