Monday, September 8, 2014

Reading Properties file in Java

Properties file are important as they help in building configurable system. For example you many not to hard code your username and passwords in the code, as those access credentials might change from environment to environment. You may also want to put the configurable parameters in the properties file. 

A properties file can be read either from class path or form a file system,

Reading from classpath

Let's assume we have a file credentials.properties in the classpath

credentials.properties

key1=value1
key2=value2

To read the file, us the following code:

//Read the properties file in a reader. If you are in a static method replace this.getClass with
//ClassName.class
String fileName = "credentials.properties";
Reader reader = new BufferedReader(new InputStreamReader(
          this.getClass().getClassLoader().getResourceAsStream(fileName)));

//Instantiate a properties object and load the reader
Properties properties = new Properties();
properties.load(reader);

//Print the properties
for(Entry<Object,Object> pair:properties.entrySet()){
System.out.println("Key: " + pair.getKey() +
          " Value: " + pair.getValue());
}

This will print

Key: key2 Value: value2
Key: key1 Value: value1

The properties are loaded in a set.

Reading properties file from File System

If you want to read the properties from a file system, change the file reading code as follows. Rest of the code remains same.

// Read the properties file in a reader
String fileName = "<Location of File path>/credentials.properties";
Reader reader = new BufferedReader(new FileReader(fileName));

No comments:

Post a Comment