Getting the inputstream from a classpath resource (XML file)

Solution 1:

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.

Solution 2:

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

Solution 3:

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.

Solution 4:

ClassLoader.class.getResourceAsStream("/path/to/your/xml") and make sure that your compile script is copying the xml file to where in your CLASSPATH.