Properties Class in Java

by SushilD2 in Design > Software

176 Views, 3 Favorites, 0 Comments

Properties Class in Java

java-properties-class-example.png

The Properties class is a subclass of Hashtable. Usually Properties are configuration values managed as key/value pairs. The key identifier is used to retrieve the value like variable name used to retrieve the variable’s value.

We can use the Properties class whenever we need to store key/value pairs in which both the keys and values are strings. Some of the important features of the Properties class include:

  • Use with other classes – Properties class is used by a few other Java classes. For example, System.getProperties() returns a Properties object with environmental values.
  • Default property – The Properties class enables you to specify a default property. If a key is not associated with any value, the default property is returned.

The Constructors in the Properties Class Are:

  • Properties(): Creates an empty Properties object without any default values.Properties(Properties
  • propDefault):Creates a Properties object and uses the default values provided in propDefault.

Methods in Properties Class

Some of the important methods in the Properties class are:

  • Object setProperty(String k, String v): Maps the value v with the key k and returns the previous value associated with k.
  • String getProperty(String k):Obtains the value associated with k and returns it.
  • void store(OutputStream so, String ds) throws IOException: Writes the Property list to the output stream that is linked to so after writing ds.
  • void load(InputStream si) throws IOException: Reads a Property list form the input stream that is linked to si.

Reading System Properties Using Properties Class

package com.blogspot.geekonjava;
import java.util.Properties;
 
public class SystemPropertiesDemo {
 
    public static void main(String[] args) {
        Properties properties = System.getProperties();
        properties.list(System.out);
    }
}

Writing Data to Properties Class Dynamically

properties-file-in-java.png
package com.blogspot.geekonjava;
 
import java.util.Properties;
 
public class PropertiesWriteDemo {
 
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
 
        properties.setProperty("username", "online tutorial spoint");
        properties.setProperty("password", "123456");
 
        properties.store(new FileWriter("dbprops.properties"), "Db-Configurations");
    }
}

Full Article

Java Properties Class Example | Geek On Java - Hub for Java and Android :

http://geekonjava.blogspot.com/2015/10/java-properties-class-example.html