In Java web application, Suppose if I want to get the InputStream of an XML file, which is placed in the CLASSPATH (i.e. inside the sources folder), how do I do it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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:
ClassLoader.class.getResourceAsStream("/path/to/your/xml")
and make sure that your compile script is copying the xml file to where in your CLASSPATH.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 useThread.currentThread().getContextClassLoader()
. See http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388.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.Some of the "getResourceAsStream()" options in this answer didn't work for me, but this one did:
SomeClassWithinYourSourceDir.class.getClassLoader().getResourceAsStream("yourResource");