opencodez

How to Read Config File in Java – With Actual Class Example rovided

In my last post I mentioned xConfig Classxcouple of times.. here you will see actual class and its usage. The class is very simple. We just need to provide proper path to config file we going to use.

The Config File Class

import java.util.*;
import java.util.Properties;

public class Config
{
   Properties configFile;
   public Config()
   {
	configFile = new java.util.Properties();
	try {
	  configFile.load(this.getClass().getClassLoader().
	  getResourceAsStream("myapp/config.cfg"));
	}catch(Exception eta){
	    eta.printStackTrace();
	}
   }

   public String getProperty(String key)
   {
	String value = this.configFile.getProperty(key);
	return value;
   }
}

You can get any property/settings from config with method xgetPropertyx

Here is my config sample file

#This is comment
mDbUser = myuser
mDbHost = myserver
mDbPwds = mypwd
mDbName = mydb

Usage:

cfg = new Config();
dbname   = cfg.getProperty("mDbUser");

I hope you find this useful. If you wish to read more Java articles from our site visit this.