88

在 Java Web 应用程序中,假设我想获取一个 XML 文件的 InputStream,该文件位于 CLASSPATH 中(即在文件夹中),我该怎么做?

4

7 回答 7

112

ClassLoader.getResourceAsStream().

如下面评论中所述,如果您处于多ClassLoader环境(例如单元测试、webapps 等)中,您可能需要使用Thread.currentThread().getContextClassLoader(). 请参阅http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388

于 2009-04-27T12:08:38.820 回答
34
ClassLoader.class.getResourceAsStream("/path/file.ext");
于 2010-11-04T03:48:33.227 回答
12

这取决于 XML 文件的确切位置。它是在源文件夹中(在“默认包”或“根”中)还是在与类相同的文件夹中?

在前一种情况下,您必须使用“ /file.xml”(注意前导斜杠)来查找文件,并且您使用哪个类来尝试定位它并不重要。

如果 XML 文件位于某个类旁边,那么SomeClass.class.getResourceAsStream()只需使用文件名即可。

于 2009-04-27T12:26:29.587 回答
11

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

于 2009-04-27T13:43:56.827 回答
6

someClassWithinYourSourceDir.getClass().getResourceAsStream();

于 2009-04-27T12:09:07.633 回答
4

此答案中的某些“getResourceAsStream()”选项对我不起作用,但这个选项可以:

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

于 2014-08-06T15:46:57.900 回答
0

我尝试了建议的解决方案,文件名中的正斜杠对我不起作用,例如: ...().getResourceAsStream("/my.properties"); 返回了 null

删除斜线有效: ....getResourceAsStream("my.properties");

以下是来自 doc 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'). 
于 2018-01-29T19:18:40.537 回答