Get All Key Values from Properties File

Get All Key Values from Properties File Get All Key Values from Properties File in java using the Properties class Available in java.util Package. The Properties class extends the Hashtable class. From Hashtable, Properties class inherits the Method KeySet() which Returns a Set view of the keys Contained in this Map.
Project Structure:-
get all key values from properties file

Example to Read All Key Values from Properties File:-

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;


public class ReadAllValues {
 
	public static void main(String[] args) {
 
	  try{
		 
		  Properties prop =loadPropertiesFile();
		  
		 Set<Object> set = prop.keySet();
		 
		 System.out.println("Reading all key values from properties file \n");
		 
		 for(Object o: set){
			 String key = (String)o;
			 System.out.println("key "+key+" value "+prop.getProperty(key));
		 }		 
	   }
	  catch(Exception ex){
		  ex.printStackTrace();
	   }
	}
	
	
	public static Properties loadPropertiesFile() throws Exception
	{
		
		Properties prop = new Properties();
                InputStream in = new FileInputStream("jdbc.properties");
                prop.load(in);
                in.close();
		return prop;
	}
}

jdbc.properties file

MYSQLJDBC.driver=com.mysql.jdbc.Driver
MYSQLJDBC.url=jdbc:mysql://localhost:3306/
MYSQLJDBC.username=root
MYSQLJDBC.password=root123

output:-

Reading all key values from properties file 

key MYSQLJDBC.url value jdbc:mysql://localhost:3306/
key MYSQLJDBC.username value root
key MYSQLJDBC.driver value com.mysql.jdbc.Driver
key MYSQLJDBC.password value root

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. This class is thread-safe, multiple threads can share a single Properties object without the need for external synchronization.

Leave a Comment