
Question:
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
Solution:1
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.
Solution:2
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.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon