Skip to content
Related Articles

Related Articles

Properties Class in Java
  • Difficulty Level : Medium
  • Last Updated : 24 Nov, 2020

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. It belongs to java.util package. Properties define the following instance variable. This variable holds a default property list associated with a Properties object. 

Properties defaults: This variable holds a default property list associated with a Properties object.
 

Features of Properties class:

  • Properties is a subclass of Hashtable.
  • It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file.
  • Properties class can specify other properties list as it’s the default. If a particular key property is not present in the original Properties list, the default properties will be searched.
  • Properties object does not require external synchronization and Multiple threads can share a single Properties object.
  • Also, it can be used to retrieve the properties of the system.

Advantage of a Properties file

In the event that any data is changed from the properties record, you don’t have to recompile the java class. It is utilized to store data that is to be changed habitually.



Note: The Properties class does not inherit the concept of a load factor from its superclass, Hashtable.

Declaration

public class Properties extends Hashtable<Object,​Object>

Constructors of Properties 

1. Properties(): This creates a Properties object that has no default values. 

Properties p = new Properties();

2. Properties(Properties propDefault): The second creates an object that uses propDefault for its default value. 

Properties p = new Properties(Properties propDefault);

Example 1: The below program shows how to use Properties class to get information from the properties file. 

Let us create a properties file and name it as db.properties.



db.properties

username = coder
password = geeksforgeeks

Code

Java




// Java program to demonstrate Properties class to get
// information from the properties file
  
import java.util.*;
import java.io.*;
public class GFG {
    public static void main(String[] args) throws Exception
    {
        // create a reader object on the properties file
        FileReader reader = new FileReader("db.properties");
  
        // create properties object
        Properties p = new Properties();
  
        // Add a wrapper around reader object
        p.load(reader);
  
        // access properties data
        System.out.println(p.getProperty("username"));
        System.out.println(p.getProperty("password"));
    }
}

Output

print properties of a file

Example 2: The below program shows how to use the Properties class to get all the system properties. Using System.getProperties() method, we can get all the properties of the system.

Java




// Java program to demonstrate Properties class to get all
// the system properties
  
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] args) throws Exception
    {
        // get all the system properties
        Properties p = System.getProperties();
  
        // stores set of properties information
        Set set = p.entrySet();
  
        // iterate over the set
        Iterator itr = set.iterator();
        while (itr.hasNext()) {
  
            // print each property
            Map.Entry entry = (Map.Entry)itr.next();
            System.out.println(entry.getKey() + " = "
                               + entry.getValue());
        }
    }
}

Output

get all the system properties

Example 3: The below program shows how to use the Properties class to create a properties file.

Java




// Java program to demonstrate Properties class to create
// the properties file
  
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] args) throws Exception
    {
        // create an instance of Properties
        Properties p = new Properties();
  
        // add properties to it
        p.setProperty("name", "Ganesh Chowdhary Sadanala");
        p.setProperty("email",
                      "ganeshs.gfg@gmail.com");
  
        // store the properties to a file
        p.store(new FileWriter("info.properties"),
                "GeeksforGeeks Properties Example");
    }
}

Output

use Properties class to create a properties file.

Methods of Properties

METHOD

DESCRIPTION

getProperty​(String key)Searches for the property with the specified key in this property list.
getProperty​(String key, String defaultValue)Searches for the property with the specified key in this property list.
list​(PrintStream out)Prints this property list out to the specified output stream.
list​(PrintWriter out)Prints this property list out to the specified output stream.
load​(InputStream inStream)Reads a property list (key and element pairs) from the input byte stream.
load​(Reader reader)Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format.
loadFromXML​(InputStream in)Loads all of the properties represented by the XML document on the specified input stream into this properties table.
propertyNames()Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.
save​(OutputStream out, String comments)

Deprecated.

This method does not throw an IOException if an I/O error occurs while saving the property list.

setProperty​(String key, String value)Calls the Hashtable method put.
store​(OutputStream out, String comments)Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.
store​(Writer writer, String comments)Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method.
storeToXML​(OutputStream os, String comment)Emits an XML document representing all of the properties contained in this table.
storeToXML​(OutputStream os, String comment, String encoding)Emits an XML document representing all of the properties contained in this table, using the specified encoding.
storeToXML​(OutputStream os, String comment, Charset charset)Emits an XML document representing all of the properties contained in this table, using the specified encoding.
stringPropertyNames()Returns an unmodifiable set of keys from this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

Methods declared in class java.util.Hashtable

METHOD

DESCRIPTION

clear()Clears this hashtable so that it contains no keys.
 clone()Creates a shallow copy of this hashtable.
compute​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent​(K key, Function<? super K,​? extends V> mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
contains​(Object value)Tests if some key maps into the specified value in this hashtable.
containsKey​(Object key)Tests if the specified object is a key in this hashtable.
containsValue​(Object value)Returns true if this hashtable maps one or more keys to this value.
elements()Returns an enumeration of the values in this hashtable.
entrySet()Returns a Set view of the mappings contained in this map.
equals​(Object o)Compares the specified Object with this Map for equality, as per the definition in the Map interface.
get​(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
hashCode()Returns the hash code value for this Map as per the definition in the Map interface.
isEmpty()Tests if this hashtable maps no keys to values.
keys()Returns an enumeration of the keys in this hashtable.
keySet()Returns a Set view of the keys contained in this map.
merge​(K key, V value, BiFunction<? super V,​? super V,​? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
put​(K key, V value)Maps the specified key to the specified value in this hashtable.
putAll​(Map<? extends K,​? extends V> t)Copies all of the mappings from the specified map to this hashtable.
rehash()Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.
remove​(Object key)Removes the key (and its corresponding value) from this hashtable.
size()Returns the number of keys in this hashtable.
toString()Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ” , ” (comma and space).
values()Returns a Collection view of the values contained in this map.

Methods declared in interface java.util.Map

METHOD

DESCRIPTION

forEach​(BiConsumer<? super K,​? super V> action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault​(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
putIfAbsent​(K key, V value)If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove​(Object key, Object value)Removes the entry for the specified key only if it is currently mapped to the specified value.
replace​(K key, V value)Replaces the entry for the specified key only if it is currently mapped to some value.
replace​(K key, V oldValue, V newValue)Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll​(BiFunction<? super K,​? super V,​? extends V> function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :