ez accessing java properties file
In java, people usually access their properties file via java.util.Properties. But, we can easily access our properties file, using java.util.ResourceBundle. How can it be?
First of all, we need a properties file. It’s a simple file, contains only key-value-pair String. For example, we have db.properties file like thisĀ :
db1.uri=jdbc:mysql://localhost:3306/db
db1.driver=com.mysql.jdbc.Driver
db1.user=root
db1.password=
where do this file take place? just simple, palce that file in your classes folder which contains class file that would access this file. For example, using eclipse, if you create the access class file in src/some/pkg/YourClass, you must place at least in src/ folder or inside sub-folder (or package) in src/.
Now, we can create a Java class to access this db.properties file using :
ResourceBundle rb = ResourceBundle.getBundle("db");
//if you place db.properties in src/some/pkg you use this code below
ResourceBundle rb = ResourceBundle.getBundle("some.pkg.db");
To get the value of key db1.uri in this properties file, just use this code :
rb.getString("db1.uri");
ok. Hope this would be helpful.
2 comments so far
Leave a reply
nice code, realy helpfull for starters like me
Thanks. Was trying to use the properties method but this is better….