How to load/read properties file from java code

Below java class will enable us to load and read the properties file. In one of the previous tutorial we have written to the properties file so keeping that in mind once after we run this program we will get the desired output. For earlier tutorial please click here

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

public class LoadProperties {
    public static void main(String[] args) {
        Properties prop = new Properties();
        try {
            // load a properties file
            prop.load(new FileInputStream("config.properties"));

            // get the property value and print it out
            System.out.println(prop.getProperty("url"));
            System.out.println(prop.getProperty("username"));
            System.out.println(prop.getProperty("password"));
            // below line will print null as it doesn't exist
            System.out.println(prop.getProperty("will print null"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


Output:

host IP Address
Amzi
passw0rd
null

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India.
    or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete