getResourceAsStream()
is the method of java.lang.Class
class. This method finds the resource with given name into the classpath. Actually this method delegates to this object's class loader. In this example PropUtil
object's class loader. But before delegation, an absolute resource name is constructed from the given resource name using following algorithm.
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.
The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load . properties file in the form of key-value pairs.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
If you use the static method and load the properties file from the classpath folder so you can use the below code :
//load a properties file from class path, inside static method Properties prop = new Properties(); prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));
final Properties properties = new Properties(); try (final InputStream stream = this.getClass().getResourceAsStream("foo.properties")) { properties.load(stream); /* or properties.loadFromXML(...) */ }
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