简体   繁体   English

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

[英]Getting the inputstream from a classpath resource (XML file)

在Java Web应用程序中,假设我要获取放置在CLASSPATH中(即, sources文件夹中)的XML文件的InputStream,该怎么办?

ClassLoader.getResourceAsStream() . ClassLoader.getResourceAsStream()

As stated in the comment below, if you are in a multi- ClassLoader environment (such as unit testing, webapps, etc.) you may need to use Thread.currentThread().getContextClassLoader() . 如下面的注释所述,如果您处于多ClassLoader环境(例如单元测试,webapp等)中,则可能需要使用Thread.currentThread().getContextClassLoader() See http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388 . 参见http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388

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

That depends on where exactly the XML file is. 这取决于XML文件的确切位置。 Is it in the sources folder (in the "default package" or the "root") or in the same folder as the class? 它在源文件夹中(在“默认包”或“根”中)还是在与类相同的文件夹中?

In for former case, you must use " /file.xml " (note the leading slash) to find the file and it doesn't matter which class you use to try to locate it. 对于前一种情况,您必须使用“ /file.xml ”(请注意斜杠)来查找文件,并且使用哪个类尝试查找文件都没有关系。

If the XML file is next to some class, SomeClass.class.getResourceAsStream() with just the filename is the way to go. 如果XML文件位于某个类的旁边, SomeClass.class.getResourceAsStream()使用文件名的SomeClass.class.getResourceAsStream()即可。

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

someClassWithinYourSourceDir.getClass()。getResourceAsStream();

Some of the "getResourceAsStream()" options in this answer didn't work for me, but this one did: 此答案中的某些“ getResourceAsStream()”选项对我不起作用,但此选项可以:

SomeClassWithinYourSourceDir.class.getClassLoader().getResourceAsStream("yourResource"); SomeClassWithinYourSourceDir.class.getClassLoader()。getResourceAsStream(“ yourResource”);

I tried proposed solution and forward slash in the file name did not work for me, example: ...().getResourceAsStream("/my.properties"); 我尝试了建议的解决方案,文件名中的正斜杠对我不起作用,例如:...()。getResourceAsStream(“ / my.properties”); null was returned 返回null

Removing the slash worked: ....getResourceAsStream("my.properties"); 删除斜线有效:.... getResourceAsStream(“ my.properties”);

Here is from doc API: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm: 这是来自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'). 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM