简体   繁体   English

java - 从jar读取xml文件

[英]java - reading xml file from jar

I am trying to read the an xml configuration from a jar file deployed to dm-server 我试图从部署到dm-server的jar文件中读取xml配置

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. 如果我只是用jar和没有dm-server写一个junit测试,我就能读懂它。

the test is packed into the jar and is at the root of the jar file. 测试被打包到jar中,并且位于jar文件的根目录下。

please help!!!! 请帮忙!!!!

thanks, A 谢谢

ClassLoader.getResourceAsStream() will allow you to read resources from within a .jar file. ClassLoader.getResourceAsStream()允许您从.jar文件中读取资源。 If your file is at the root of the .jar file then: 如果您的文件位于.jar文件的根目录,则:

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

will give you an InputStream from that file. 将从该文件中为您提供一个InputStream。

You need to use the Class's getResource or getResourceAsStream methods to read files from within the jar. 您需要使用Class的getResourcegetResourceAsStream方法从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. 请注意,如果getResourceAsStream找不到该文件,则返回null。

Edit: Corrected test.xml to /test.xml 编辑:将test.xml更正为/test.xml

Also note that the Class<T> version of getResourceAsStream defers to the ClassLoader 's getResourceAsStream or getSystemResourceAsStream as appropriate. 另请注意, getResourceAsStreamClass<T>版本会根据需要getResourceAsStream ClassLoadergetResourceAsStreamgetSystemResourceAsStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM