Reading Property File using Java

In this tutorial, I am attaching Simple program about Reading Property File using Java. The example Java Program were tested with environment and output is shared in the same post.

ReadPropertyFile.java

package com.dineshkrish.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* 
* @author Dinesh Krishnan
*
*/
public class ReadPropertyFile {
public static void main(String[] args) {
// Property File
File propertyFile = new File("myproperty.properties");
try {
// Defining FileInputStream Object
FileInputStream fis = new FileInputStream(propertyFile);
// Defining Properties Object
Properties properties = new Properties();
// Loading the InputStream (ie: FileInputStream) Object
properties.load(fis);
String firstName = properties.getProperty("label.firstname"); // Get Value by passing Key
String lastName = properties.getProperty("label.lastname");
String greetingMessage = properties.getProperty("label.greetingmessage");
System.out.println("Hello everyone,");
System.out.println(greetingMessage);
System.out.println("\nRegards");
System.out.println("------------------");
System.out.println(firstName+" "+lastName);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

myproperty.properties

The properties files are basically used to store configuration data in form of Key-Value pair. you see the content of the myproperty.properties file below.

#This is property file

label.firstname = Dinesh
label.lastname = Krishnan
label.greetingmessage = Thanks for reading my articles.

# You can add Key-Value pair accordingly

Output

—————–
Hello everyone,
Thanks for reading my articles.

Regards
——————
Dinesh Krishnan

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *