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

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) {

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.*;

public class ConfigReader {

  private String fileName;
  private Properties properties;

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

  public void printPropertyList() {

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

  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.");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: