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?
We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With