Read Properties File using java

To Read Properties File in Java, the Properties Class has a Convenient load Method. That’s the Easiest Way to Read a Java Properties File. Properties are Configuration Values Managed as key/value Pairs. In Each Pair, the key and value are Both String Values. The key Identifies, and is Used to Retrieve, the Value, much as a Variable Name is Used to Retrieve the Variable’s Value. The java.util.Properties Package Contains the Properties File Using which We can Read Properties File.
Project Structure:-

read properties file

Using Below Code We can Read Properties File

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


public class ReadPropertiesFile {
 
	public static void main(String[] args) {
 
	  try{
		 
		  Properties prop =loadPropertiesFile();
		  
		  String driver = prop.getProperty("MYSQLJDBC.driver");
		  String url = prop.getProperty("MYSQLJDBC.url");
		  String username = prop.getProperty("MYSQLJDBC.username");
		  String password =prop.getProperty("MYSQLJDBC.password");
	      
		  System.out.println(" read properties file and getting connection detail ");
		 
		  System.out.println(" driver name is "+driver);
		  System.out.println(" url is "+url);
		  System.out.println(" username is "+username);
		  System.out.println(" password is "+password);
	  
	   }
	  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;
	}
}

output:-

 
 read properties file and getting connection detail
 driver name is com.mysql.jdbc.Driver
 url is jdbc:mysql://localhost:3306/
 username is root
 password is root123

jdbc.properties File

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

Leave a Comment