Saturday, February 8, 2014

Storing configuration data for JAVA applications

       Many times it is required to store some configuration settings for your application so that it can use again and again from where it left.Or the application can start with some specific parameters.So the properties file can come handy in such requirements.

   First lets write something to the properties file..

Code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class App {
  public static void main(String[] args) {

    Properties prop = new Properties();
    OutputStream output = null;

    try {

        output = new FileOutputStream("C:\\Alberto\\Config\\debug.properties");
        prop.setProperty("stat","no");
        prop.setProperty("mail", "oksbwn@gmail.com");
        prop.setProperty("id", "oksbwn");
        prop.store(output, null);
       } catch (Exception io) {io.printStackTrace();}  
    }
}

Simillarly you can add more parameters using  setProperty() function.Now lets see how to read from a property file..
Code:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class read {
  public static void main(String[] args) {

    Properties prop = new Properties();
    InputStream input = null;

    try {

        input = new FileInputStream("config.properties");
        prop.load(input);
        System.out.println(prop.getProperty("database"));
        System.out.println(prop.getProperty("dbuser"));
        System.out.println(prop.getProperty("dbpassword"));

    } catch (Exception ex) {ex.printStackTrace();}
   }
}


Thanks...

No comments:

Post a Comment