Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the inputstream from a classpath resource (XML file)

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?

like image 925
Veera Avatar asked Apr 27 '09 12:04

Veera


People also ask

How do I load resources from classpath?

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.

What is InputStream from a file?

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .


2 Answers

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.

like image 82
cletus Avatar answered Sep 27 '22 19:09

cletus


ClassLoader.class.getResourceAsStream("/path/file.ext"); 
like image 39
jkarretero Avatar answered Sep 27 '22 21:09

jkarretero