Loading configuration parameters from textfile into a program


Loading parameters into a program is easily handled in Java through the Properties class.
The only thing that has to be done is to create an instance of the Properties class and one instance of
FileInputStream class that points to the configuration file.
The actual loading of the parameters are done through the method load() on the Properties object.
In the example below parameters are read from the configuration file and then printed out.

This is what the sample configuration file looks like:


# System configuration
# Comments will automatically be excluded by the program.

parameter1=value1

parameter2=value2




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

/**
 * Main.java
 *
 * @author www.javadb.com
 */


public class Main {
    
    Properties config;
    
    /**
     * Loads configuration parameters from a textfile and print them out.
     */

    public void loadConfigFile() {

        //Load configuration file
        String filename = "conf/systemconfig.txt";
        config = new Properties();

        try {

            config.load(new FileInputStream(filename));

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
            return;
        }
        
         
        //Print out the configuration parameters
        Enumeration en = config.keys();
        
        System.out.println("********** System configuration **********");
        while (en.hasMoreElements()) {
            
            String key = (String) en.nextElement();
            System.out.println(key + " => " + config.get(key));
            
        }
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().loadConfigFile();
    }
}


This is the output after printing out the loaded configuration parameters:


********** System configuration **********
parameter2 => value2
parameter1 => value1