How to Read Config File in Java – With Actual Class Example rovided
In my last post I mentioned “Config Class”couple 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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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 ‘getProperty’
Here is my config sample file
|
1 2 3 4 5 |
#This is comment mDbUser = myuser mDbHost = myserver mDbPwds = mypwd mDbName = mydb |
Usage:
|
1 2 |
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.
22 Comments

how to read multiple .cfg file
very helpful and clean. Maybe few comment can add more value
usage
Config cfg = new Config();
String dbname = cfg.getProperty(“mDbUser”);