Reading Configuration File In Java

Reading Configuration File In Java

In order to make a program more flexible, it is normal to create an external file to store all the setting. For example, resolution setting of a game is saved in “config.ini” or “settings.prop” so that we can easily modify a program without recompile it. Here I would show you how to do it.

First, we create a config file (you can name it with any name you want as Java read its text only).

# comment  
! comment again  
Surname=Backham  
Othername=Peter  

Second, you need to use the Java API properties to read in the config text.

try {  
    properties = new Properties();  
    properties.load(new FileInputStream("config.ini"));  
} catch (Exception e) {  
    System.out.println(e);  
}  

Alternatively, I had created a class for it. You may copy it if you like, just don’t modify it. =]

/*  
 * Code by Nicholas Wong. Copyright reserved.  
 * Usage:  
 * ConfigReader configReader = new ConfigReader("config.ini");  
 * SshConnectorOld.hostname = configReader.getProperty("Surname");  
 */

import java.util.*;  
import java.io.*;

public class ConfigReader {

    private String fileName;  
    private Properties properties;

    public String getProperty(String propName) {  
        return properties.getProperty(propName);  
    }

    public void printPropertyList() {  
        properties.list(System.out);  
    }

    public ConfigReader(String fileName) {  
        this.fileName = fileName;  
        readProperties();  
    }

    private static String getClassPath() {  
        StringBuffer classLocation = new StringBuffer();  
        final String className = SshConnectorOld.class.getName().replace(‘.’, ‘/’) + ".class";  
        final ClassLoader classloader = SshConnectorOld.class.getClassLoader();

        if (classloader == null) {  
            System.out.println("Cannot load the class");  
            return null;  
        } else {  
            String[] classLocationArray = classloader.getResource(className).toString().substring(6).split("/");  
            for (int i = 0; i<classLocationArray.length-2; i++) {  
                classLocation.append(classLocationArray[i] + "/");  
            }  
            return classLocation.toString();  
        }  
    }

    private void readProperties() {  
        try {  
            properties = new Properties();  
            properties.load(new FileInputStream(getClassPath() + fileName));  
            System.out.println("Configuration file is read successfully.");  
        } catch (Exception e) {  
            System.out.println("Configuration file reading failed.");  
            System.out.println(e);  
        }  
    }  
}