Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java—从jar读取xml文件_Java_Xml_Jakarta Ee - Fatal编程技术网

java—从jar读取xml文件

java—从jar读取xml文件,java,xml,jakarta-ee,Java,Xml,Jakarta Ee,我试图从部署到dm服务器的jar文件中读取xml配置 这是密码 Reader fileReader = null; try { fileReader = new FileReader("test.xml"); } catch (FileNotFoundException fnfex) { fnfex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } 如果我只编写一个junit测试,不使用ja

我试图从部署到dm服务器的jar文件中读取xml配置

这是密码

Reader fileReader = null;
try {
 fileReader = new FileReader("test.xml");
} catch (FileNotFoundException fnfex) {
 fnfex.printStackTrace();
} catch (IOException ioex) {
 ioex.printStackTrace();
}
如果我只编写一个junit测试,不使用jar,不使用dm服务器,我就能够阅读它

测试打包到jar中,位于jar文件的根目录下

请帮忙

谢谢, 将允许您从.jar文件中读取资源。如果文件位于.jar文件的根目录下,则:

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

将从该文件中为您提供一个InputStream。

您需要使用类的
getResource
getResourceAsStream
方法从jar中读取文件

可以这样做:

Reader fileReader = null;

InputStream is = this.getClass().getResourceAsStream("/test.xml");
if (null != is) {
    fileReader = new InputStreamReader(is);
}
请注意,
getResourceAsStream
如果找不到文件,则返回null

编辑: 已将test.xml更正为/test.xml


还要注意的是,
Class
版本的遵从于
ClassLoader
,或者视情况而定。

getResourceAsStream返回null,我在jar的根目录中有xml,这是调用它的正确方法吗?InputStream=this.getClass().getResourceAsStream(“test.xml”)@沙阿:我错了,看来在
test.xml
之前你确实需要一个
/
。我会马上修复它。我尝试了这个,但它仍然为我返回空值。我将文件放在“资源”文件夹中。可能存在的重复项