从类路径资源(XML文件)获取输入流

91
在Java Web应用程序中,假设我想要获取位于CLASSPATH(即sources文件夹内)的XML文件的InputStream,我该怎么做?
答案:
7个回答

114

请查看个人帖子以获取代码示例:http://tshikatshikaaa.blogspot.nl/2012/07/maven-how-to-access-filesdata-in.html - Jérôme Verstrynge
14
如果您处于多类加载器环境中(例如单元测试/ Web 应用程序等),则可能需要使用 Thread.currentThread().getContextClassLoader()。请参见 https://dev59.com/TXE95IYBdhLWcg3wb9hb#OqSeEYcBWogLw_1bdm5l。 - khylo
请将@khylo的建议添加到您的答案中! - froginvasion
10
另一种方式:InputStream is = new ClassPathResource("/path/to/your/file").getInputStream() - zhuguowei
2
@zhuguowei ClassPathResource 是 Spring 框架中的一个类。 - ichalos

34
ClassLoader.class.getResourceAsStream("/path/file.ext");

1
但是如果以这种方式在Tomcat中部署Web应用程序,将会出现错误:java.lang.NullPointerException: null。我认为最简单的方法是使用new ClassPathResource("/path/to/your/file").getInputStream() - zhuguowei
1
请问您能告诉我如何将其打包成war文件并使其可用吗? - Vikram Saini
当我部署时,我遇到了同样的问题。有人找到了解决这种情况的方法吗? - Augusto

13

这取决于XML文件的具体位置。它是在源文件夹中(在“默认包”或“根目录”中)还是与类文件在同一文件夹中?

如果是前者,您必须使用 "/file.xml"(注意前导斜杠)来查找该文件,并且您尝试定位它使用哪个类并不重要。

如果XML文件与某个类文件相邻,SomeClass.class.getResourceAsStream() 后跟文件名就可以了。


11

ClassLoader.class.getResourceAsStream("/path/to/your/xml") 要确保你的编译脚本将xml文件复制到CLASSPATH所在的位置。


6

someClassWithinYourSourceDir.getClass().getResourceAsStream();


或者 getClass().getResourceAsStream("...") 等等。 - rogerdpack

4

我发现这个答案中的一些“getResourceAsStream()”选项对我无效,但是这个有效:

SomeClassWithinYourSourceDir.class.getClassLoader().getResourceAsStream("yourResource");


0

我尝试了提出的解决方案,但在文件名中使用斜杠对我没有起作用,例如:...().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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接