Reading Properties from a File

It’s not too much trouble to read a few arguments from the command line. It really becomes a problem if you have to read 50 or more arguments. One solution is to prepare a property file and mention all the properties in it. Then you can read the name of the property file from the command line and read the values of all other properties when you need to throughout the application. The syntax of the property file should be in the following format.

 key=value

Keys can be defined in a separate Java class, say PropertyDefiner, and can be implemented as a singleton.

 public static final String CONFIGURATION_FILE = key_in_property_file;

Make use of the java.util.Properties class that represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream.

             //instantiate a new Property class            Properties props = new Properties();// set the name of the property fileif (args[i].equalsIgnoreCase("-f"))props.setProperty(PropertyDefiner.CONFIGURATION_FILE, args[++i]);

Just for the sake of robustness, check if this file is not null while retrieving the file name. Once you have the file name, open a FileInputStream and load the properties. And don’t forget to close the input stream once the job is done.

 	FileInputStream in = new FileInputStream(fileName);	props.load(in);	in.close();

Now you can retrieve the value of any property as you wish.

 String propertyName = props.getProperty(PropertyDefiner.PROPERTY_NAME);

Using this approach, you can add new properties while you are developing the application. You also can fine-tune the performance of your application by merely changing a few values in the property file.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: