Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load property file from classpath? [closed]

Tags:

java

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.

like image 378
Kashif Raza Avatar asked Aug 19 '12 06:08

Kashif Raza


People also ask

How do I load a file 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.

How do I load a property file?

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.

How do you load properties file from resources folder in Java?

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().


2 Answers

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")); 
like image 53
Keval Trivedi Avatar answered Sep 20 '22 22:09

Keval Trivedi


final Properties properties = new Properties(); try (final InputStream stream =            this.getClass().getResourceAsStream("foo.properties")) {     properties.load(stream);     /* or properties.loadFromXML(...) */ } 
like image 36
obataku Avatar answered Sep 23 '22 22:09

obataku