Properties in java - java.util.Properties - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Sunday, January 15, 2017

Properties in java - java.util.Properties

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.

java properties file is used to store string key-value pair and java Properties class is used to worked with properties file in java. Java Properies class inherits from Hashtable. It can be used to get properties value based on key. The Properties class provides methods to get data from file and store key-value data into file.

Advantage of properties file

All the configurable data can be put into properties files, when data changed into properties files, no need to recompile the java class. Recompilation is not recquired, if information changed in properties files. Mostly properties file store information which is to be changed frequently and configurable data like information about database etc.

Default root directory in java

Novice java developer struggle to find the root directory of the project to keep the properties file under it. Core java and J2EE have different folder structure, in J2EE properties files store under resources folder, so developer get confused to store properties file in core java.

You can find the default root directory in java using the following line.

System.getProperty("user.dir")

Java properties file

Java properties file can be a normal property file with key-value pair or it can be also a xml file. Here, we will discuss both way to store and read files.

We will also show you how to load properties file from classpath and how to read all the keys from the properties file.

java.util.Properties examples

find the working code from here.

Topic cover in the below code.

  • Read normal properties file and xml file from root directory.
  • Read properties files from classpath.
  • Read properties file and assign default value if key is not available in file.
  • Get all the keys of properties files.
  • Store string key-value pairs in properties files.

db.properies and db.xml properties files are under root directory.

database.properties and database.xml files are under src folder(classpath).

db.properies or database.properties and db.xml or database.xml all files contain the same string key-value pairs.

db.properties

db.username=root
db.password=root
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/test

db.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <entry key="db.username">root</entry>
  <entry key="db.password">root</entry>
  <entry key="db.driver">com.mysql.jdbc.Driver</entry>
  <entry key="db.url">jdbc:mysql://127.0.0.1:3306/test</entry>
</properties>
PropertiesFileDemo.java
package com.walking.techie.properties;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

public class PropertiesFileDemo {

  public static void main(String[] args) {

    String propertiesFileName = "db.properties";
    String xmlPropertiesFile = "db.xml";
    String classpathPropertiesFile = "database.properties";
    String xmlClasspathPropertiesFile = "database.xml";

    readPropertiesFile(propertiesFileName, xmlPropertiesFile);
    System.out.println();
    readFilesFromClasspath(classpathPropertiesFile, xmlClasspathPropertiesFile);
    System.out.println();
    //assign default value for unavailable key in properties file
    assignDefaultValue(propertiesFileName);
    System.out.println();
    //get all keys from properties file
    readAllKeys(propertiesFileName, xmlPropertiesFile);
    System.out.println();
    writePropertiesFile(propertiesFileName, xmlPropertiesFile);
  }


  private static void readPropertiesFile(String propertiesFileName, String xmlPropertiesFile) {
    System.out.println("**********Reading properties file**************");
    Properties properties = new Properties();
    try {
      FileReader fileReader = new FileReader(propertiesFileName);

      properties.load(fileReader);

      System.out.println("User Name: " + properties.getProperty("db.username"));
      System.out.println("Password: " + properties.getProperty("db.password"));
      System.out.println("Url: " + properties.getProperty("db.url"));
      System.out.println("Driver: " + properties.getProperty("db.driver"));
      System.out.println("*******End of reading normal properties file*******");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    properties.clear();
    System.out.println("*******Reading xml properties file**************");
    try {
      InputStream inputStream = new FileInputStream(xmlPropertiesFile);

      try {
        properties.loadFromXML(inputStream);
        System.out.println("User Name: " + properties.get("db.username"));
        System.out.println("Password: " + properties.getProperty("db.password"));
        System.out.println("Url: " + properties.getProperty("db.url"));
        System.out.println("Driver: " + properties.getProperty("db.driver"));
        System.out.println("*******End reading xml properties file*******");
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }

  private static void readFilesFromClasspath(String classpathPropertiesFile,
      String xmlClasspathPropertiesFile) {
    System.out.println("*****Reading properties file from classpath******");

    Properties properties = new Properties();
    InputStream inputStream = PropertiesFileDemo.class
        .getResourceAsStream("/" + classpathPropertiesFile);
    try {
      properties.load(inputStream);
      System.out.println("User Name: " + properties.getProperty("db.username"));
      System.out.println("Password: " + properties.getProperty("db.password"));
      System.out.println("Url: " + properties.getProperty("db.url"));
      System.out.println("Driver: " + properties.getProperty("db.driver"));
      System.out.println("*******End of reading normal properties file from classpath*******");
    } catch (IOException e) {
      e.printStackTrace();
    }

    properties.clear();
    System.out.println("*******Reading xml properties file from classpath**********");
    inputStream = PropertiesFileDemo.class.getResourceAsStream("/" + xmlClasspathPropertiesFile);

    try {
      properties.loadFromXML(inputStream);
      System.out.println("User Name: " + properties.getProperty("db.username"));
      System.out.println("Password: " + properties.getProperty("db.password"));
      System.out.println("Driver: " + properties.getProperty("db.driver"));
      System.out.println("Url: " + properties.getProperty("db.url"));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private static void assignDefaultValue(String propertiesFileName) {
    System.out.println("**********Reading properties file**************");
    Properties properties = new Properties();
    try {
      FileReader fileReader = new FileReader(propertiesFileName);

      properties.load(fileReader);

      System.out.println("User Name: " + properties.getProperty("db.username"));
      System.out.println("Password: " + properties.getProperty("db.password"));
      //value is not available corresponding to db.host so default value localhost will print
      System.out.println("Host: " + properties.getProperty("db.host", "localhost"));
      System.out.println("*******End of reading normal properties file*******");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  private static void readAllKeys(String propertiesFileName, String xmlPropertiesFile) {
    System.out.println("*****Reading properties file for all keys******");
    Properties properties = new Properties();
    try {
      FileReader reader = new FileReader(propertiesFileName);
      properties.load(reader);
      Set<Object> allKeys = properties.keySet();
      for (Object key : allKeys) {
        System.out.println(key + " : " + properties.getProperty((String) key));
      }
      System.out.println("***End of reading normal properties file for all keys***");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    properties.clear();
    System.out.println("***Reading xml properties file for all keys***");
    try {
      InputStream inputStream = new FileInputStream(xmlPropertiesFile);
      try {
        properties.loadFromXML(inputStream);
        Set<Object> allKeys = properties.keySet();
        for (Object key : allKeys) {
          System.out.println(key + " : " + properties.getProperty((String) key));
        }
        System.out.println("***End of reading xml properties file for all keys***");
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }

  private static void writePropertiesFile(String propertiesFileName, String xmlPropertiesFile) {
    System.out.println("********Stating of writing properties file********");
    Properties properties = new Properties();
    properties.setProperty("db.host", "localhost");
    properties.setProperty("db.username", "system");
    properties.setProperty("db.password", "password");
    try {
      properties.store(new FileWriter(propertiesFileName), "db configuration file");
      System.out.println(propertiesFileName + " has written successfully");

      properties.storeToXML(new FileOutputStream(xmlPropertiesFile), "db configuration XML file");
      System.out.println(xmlPropertiesFile + " has written successfully");
      System.out.println("******end of writing properties files*********");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

In above code when you run the program, writePropertiesFile method will write property files in both the format and it will be stored in the project root directory. db.properties and db.xml file will overrride.

Below is properties files generated when we run above code.

db.properties

#db configuration file
#Sun Jan 15 21:54:56 IST 2017
db.password=password
db.host=localhost
db.username=system

db.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>db configuration XML file</comment>
<entry key="db.password">password</entry>
<entry key="db.host">localhost</entry>
<entry key="db.username">system</entry>
</properties>

Notice that above both the properties file have comments, it has generated because in the code comment is passed while writing the files.

Output of above program is shown below:

**********Reading properties file**************
User Name: root
Password: root
Url: jdbc:mysql://127.0.0.1:3306/test
Driver: com.mysql.jdbc.Driver
*******End of reading normal properties file*******
*******Reading xml properties file**************
User Name: root
Password: root
Url: jdbc:mysql://127.0.0.1:3306/test
Driver: com.mysql.jdbc.Driver
*******End reading xml properties file*******

*****Reading properties file from classpath******
User Name: root
Password: root
Url: jdbc:mysql://127.0.0.1:3306/test
Driver: com.mysql.jdbc.Driver
*******End of reading normal properties file from classpath*******
*******Reading xml properties file from classpath**********
User Name: root
Password: root
Driver: com.mysql.jdbc.Driver
Url: jdbc:mysql://127.0.0.1:3306/test

**********Reading properties file**************
User Name: root
Password: root
Host: localhost
*******End of reading normal properties file*******

*****Reading properties file for all keys******
db.password : root
db.url : jdbc:mysql://127.0.0.1:3306/test
db.username : root
db.driver : com.mysql.jdbc.Driver
***End of reading normal properties file for all keys***
***Reading xml properties file for all keys***
db.password : root
db.url : jdbc:mysql://127.0.0.1:3306/test
db.username : root
db.driver : com.mysql.jdbc.Driver
***End of reading xml properties file for all keys***

********Stating of writing properties file********
db.properties has written successfully
db.xml has written successfully
******end of writing properties files*********

Note : This code has been compiled and run on mac notebook and intellij IDEA.

find the above working code from git.

No comments :

Post a Comment