Write Config File in Java
Most of the time we use properties file only to load some fairly static values that are used across the project. Some one once asked me whether I have any sample to write the config file from java? I didn’t see much of a benefit of this. Who would want to write config file from your program and use it again. But later thought that there might be scenario where in some one want to implement this kind of stuff. He may be thinking of loading all properties from database and keep it in config file when his class is initialized and intend to use it later. After some time he may update the file and store the updated config to database in one go. Quiet possible scenario!
So here I am sharing the java code where we will write the config file, we will update it and use it. Here I have simple class PropStore.java which is going to writer config.properties for me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class PropStore { public static void main( String[] args ) { Properties prop = new Properties(); try { //set the properties value prop.setProperty("database", "localhost"); prop.setProperty("dbuser", "myuser"); prop.setProperty("dbpassword", "mypwd"); //save properties to project root folder prop.store(new FileOutputStream("c://config.properties"), null); } catch (IOException ex) { ex.printStackTrace(); } } } |
Now you can see I am writing 3 properties to my file and I am storing it to C drive. If you do not specify the path, the file will be created in project/files default path. Let me show you what we have written to properties file.
1 2 3 4 |
#Tue Jun 25 16:06:53 IST 2013 dbpassword=mypwd database=localhost dbuser=myuser |
See a nicely written properties file is ready to load and use. You can refer our article on How to Read Config File in Java to know how to load this property file.