简体   繁体   中英

Getting the inputstream from a classpath resource (XML file)

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

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() . See 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. 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.

If the XML file is next to some class, SomeClass.class.getResourceAsStream() with just the filename is the way to go.

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:

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"); null was returned

Removing the slash worked: ....getResourceAsStream("my.properties");

Here is from doc API: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

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'). 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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