tags:

views:

57

answers:

2

I am trying to read the an xml configuration from a jar file deployed to dm-server

here is the code

Reader fileReader = null;
try {
 fileReader = new FileReader("test.xml");
} catch (FileNotFoundException fnfex) {
 fnfex.printStackTrace();
} catch (IOException ioex) {
 ioex.printStackTrace();
}

i was able to read it if i just write a junit test w/o the jar and w/o the dm-server.

the test is packed into the jar and is at the root of the jar file.

please help!!!!

thanks, A

+3  A: 

ClassLoader.getResourceAsStream() will allow you to read resources from within a .jar file. If your file is at the root of the .jar file then:

this.getClass().getClassLoader().getResourceAsStream("/test.xml");

will give you an InputStream from that file.

Brian Agnew
+2  A: 

You need to use the Class's getResource or getResourceAsStream methods to read files from within the jar.

This can be done like this:

Reader fileReader = null;

InputStream is = this.getClass().getResourceAsStream("/test.xml");
if (null != is) {
    fileReader = new InputStreamReader(is);
}

Note that getResourceAsStream returns null if it can't find the file.

Edit: Corrected test.xml to /test.xml

Also note that the Class<T> version of getResourceAsStream defers to the ClassLoader's getResourceAsStream or getSystemResourceAsStream as appropriate.

R. Bemrose
getResourceAsStream returns null, i have the xml in the root of the jar, is this the correct way of calling it?InputStream is = this.getClass().getResourceAsStream("test.xml");
Shah
@Shah: My mistake, it appears you do need a `/` before `test.xml`. I'll fix it in a moment.
R. Bemrose