devxlogo

Reading Properties from a File

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist