java - 从 jar 读取 xml 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3409417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java - reading xml file from jar
提问by Shah
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
谢谢
回答by Brian Agnew
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:
ClassLoader.getResourceAsStream()将允许您从 .jar 文件中读取资源。如果您的文件位于 .jar 文件的根目录,则:
this.getClass().getClassLoader().getResourceAsStream("/test.xml");
will give you an InputStream from that file.
会给你一个来自该文件的 InputStream 。
回答by Powerlord
You need to use the Class's getResourceor getResourceAsStreammethods to read files from within the jar.
您需要使用类getResource或getResourceAsStream方法从 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 getResourceAsStreamreturns 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 getResourceAsStreamdefers to the ClassLoader's getResourceAsStreamor getSystemResourceAsStreamas appropriate.
另请注意,Class<T>版本getResourceAsStream遵循ClassLoader'sgetResourceAsStream或getSystemResourceAsStream适当。

