加载 Java 类路径中的 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4264594/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:36:06  来源:igfitidea点击:

Loading XML File which is in classpath in Java

javaxmlresourcesclasspath

提问by Narendra

I need to load a xml file present in classpath into my java applicatio. Can any one give suggestions on this.

我需要将类路径中存在的 xml 文件加载到我的 java 应用程序中。任何人都可以就此提出建议。

Thanks,
Narendra

谢谢,
纳伦德拉

回答by Jon Skeet

Use ClassLoader.getResourceAsStreamor Class.getResourceAsStream, and then load it as you would for any other InputStream.

使用ClassLoader.getResourceAsStreamClass.getResourceAsStream,然后像加载任何其他InputStream.

(The difference between using the ClassLoaderversion and the Classversion is how "relative" resource paths are resolved. With the ClassLoaderversion, it's always effectively treated as an absolute path; with the Classversion, if the path doesn't start with "/" it's treated as relative to the package of that class.)

(使用ClassLoader版本和Class版本的区别在于如何解析“相对”资源路径。对于ClassLoader版本,它总是有效地被视为绝对路径;对于Class版本,如果路径不以“/”开头,则被处理相对于该类的包。)