Monday, October 12, 2009

How to write to a .properties file dynamically from java code?

We all must have used the properties file for using our desktop\web application in different locales. But once in one of the projects I encountered a situation where we had to write the configuration settings to a properties file which were a one time activity from the end user's side.

We followed the following approach to write to a .properties file from java code

File propFile = new File(System.getProperty("user.dir")+"src\\uts\\config\\envConfig.properties");
Properties prop = new Properties();

try
{
   FileInputStream fis = new FileInputStream(propFile);
   prop.load(fis);
   prop.setProperty("env_"+environmentName, environmentName);
   prop.setProperty("uid_"+userId, userId);
   prop.setProperty("pass_"+password, password);
   prop.store(new FileOutputStream(propFile), null);
}
catch(Exception e)
{
  e.printStackTrace();
}