Reading an xml file inside a jar package

Here is 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 .jar, it can never find the values.xml.

I tried using ValueReader.class.getResource () and ValueReader.class.getResourceAsStream (), but it does not work.

What is the problem? How to get a file object into my .xml values?

IN.

+6
java xml file jar package
source share
4 answers

You cannot get the File object (since it is no longer the file after it in .jar), but you can get it as a stream via getResourceAsStream(path); where path is the full path to your class.

eg.

 /com/mycompany/resources/values.xml 
+8
source share

You cannot get File for a file because it is in a jar file. But you can get the input stream:

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

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

+2
source share

It will work ...

 Thread.currentThread().getContextClassLoader().getResource("com/mycompany/resources/values.xml") 
0
source share

You can extract the jar and then take what you want in the same class-path using:

  ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile()))); 
-one
source share

All Articles