答案:
ClassLoader.getResourceAsStream()
方法用于获取与指定名称相对应的资源作为流对象。如下方注释所述,如果您在多ClassLoader
环境中(例如单元测试、Web应用程序等),则可能需要使用Thread.currentThread().getContextClassLoader()
方法。参见https://dev59.com/TXE95IYBdhLWcg3wb9hb#OqSeEYcBWogLw_1bdm5l。
ClassLoader.class.getResourceAsStream("/path/file.ext");
java.lang.NullPointerException: null
。我认为最简单的方法是使用new ClassPathResource("/path/to/your/file").getInputStream()
。 - zhuguowei这取决于XML文件的具体位置。它是在源文件夹中(在“默认包”或“根目录”中)还是与类文件在同一文件夹中?
如果是前者,您必须使用 "/file.xml
"(注意前导斜杠)来查找该文件,并且您尝试定位它使用哪个类并不重要。
如果XML文件与某个类文件相邻,SomeClass.class.getResourceAsStream()
后跟文件名就可以了。
ClassLoader.class.getResourceAsStream("/path/to/your/xml")
要确保你的编译脚本将xml文件复制到CLASSPATH所在的位置。
someClassWithinYourSourceDir.getClass().getResourceAsStream();
getClass().getResourceAsStream("...")
等等。 - rogerdpack我发现这个答案中的一些“getResourceAsStream()”选项对我无效,但是这个有效:
SomeClassWithinYourSourceDir.class.getClassLoader().getResourceAsStream("yourResource");
我尝试了提出的解决方案,但在文件名中使用斜杠对我没有起作用,例如:...().getResourceAsStream("/my.properties"); 返回 null。
而移除斜杠后就可以正常工作:....getResourceAsStream("my.properties");
这里是 API 文档中的内容: 在委派之前,使用以下算法从给定的资源名称构造绝对资源名称:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
null
,没有斜杠。添加斜杠字符对我有用。@hussein-terek和我的设置与您的设置之间必须存在某些其他差异。 - Ajoy Bhatia
InputStream is = new ClassPathResource("/path/to/your/file").getInputStream()
。 - zhuguowei