Using Java Properties class

 


In this tutorial we will see about Java Properties class and how to use in our project to read property file values. Most of the time in our project we will be use configuration parameters like database connection details or other parameter related to project. Set the parameters in property file and read throughout the application using Java Properties.

Where here values can be easily modified or even we can add new parameters to the project through property file at run-time without reloading the context or editing any java file. 

project.properties


driver=org.postgresql.Driver
url=jdbc:postgresql://localhost/databasseName
user=postgres
password=postgres
maxconn=10
maxidle=0


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

public class PropertiesTest {

 public static void main(String[] args) {
  
  String propertyFile = "project.properties";
  
  Properties property = new PropertiesTest().readPropertyFile(propertyFile);
  
  System.out.println("DRIVER   : "+property.getProperty("driver"));
  System.out.println("URL      : "+property.getProperty("url"));
  System.out.println("USER     : "+property.getProperty("user"));
  System.out.println("PASSWORD : "+property.getProperty("password"));
  System.out.println("MAX CONN : "+property.getProperty("maxconn"));
  System.out.println("MAX IDLE : "+property.getProperty("maxidle"));
 }
 
 public Properties readPropertyFile(String propertyFile){
  Properties properties = new Properties();
  InputStream inputstream = getClass().getResourceAsStream(propertyFile);
  try {
   properties.load(inputstream);
   System.out.println("NO OF PROPERTIES ::::: " + properties.size());   
  } catch (Exception e) {
   e.printStackTrace();
  }
  return properties;
 }
}


OUTPUT:


NO OF PROPERTIES ::::: 6
DRIVER   : org.postgresql.Driver
URL      : jdbc:postgresql://localhost/databasseName
USER     : postgres
PASSWORD : postgres
MAX CONN : 10
MAX IDLE : 0







1 comment:
Write comments