Properties Class

Properties
  • Properties class is the child class of Hashtable.
  • In our program if anything which changes frequently like Database User name, Password etc., such type of values not recommended to hard code in java application because for every change we have to recompile, rebuild and redeployed the application and even server restart also required sometimes it creates a big business impact to the client.
  • Such type of variable things we have to hard code in property files and we have to read the values from the property files into java application.
  • The main advantage in this approach is if there is any change in property files automatically those changes will be available to java application just redeployment is enough.
  • By using Properties object we can read and hold properties from property files into java application.
Constructors

Properties p=new Properties();

In properties both key and value “should be String type only”.

Methods

1. String getPrperty(String propertyname) ;

Returns the value associated with specified property.

2. String setproperty(String propertyname,String propertyvalue);

To set a new property.

3. Enumeration propertyNames();

4. void load(InputStream is); //Any InputStream we can pass.

To load Properties from property files into java Properties object.

5. void store(OutputStream os,String comment);//Any OutputStream we can pass.

To store the properties from Properties object into properties file.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyProperties {
   public static void main(String[] args) throws Exception {
      Properties prop = new Properties();
      FileInputStream fis = new FileInputStream("db.properties");
      prop.load(fis);
      String url = prop.getProperty("url");
      String username = prop.getProperty("username");
      String password = prop.getProperty("password");
      Connection con = DriverManager.getConnection(url, username, password);
      ---------------------------------------------------------
      --------------------------------------------------------
      FileOutputStream fos = new FileOutputStream("db.properties");
      prop.store(fos, "Updated by Ashok");
   }
}
Properties Class

Scroll to top