Thursday, December 27, 2012

Simple way to read properties file in Java

Copy pasted from Link: http://www.mkyong.com/java/java-properties-file-examples/

package com.mkyong.common;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
 
public class App 
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
      //set the properties value
      prop.setProperty("database", "localhost");
      prop.setProperty("dbuser", "mkyong");
      prop.setProperty("dbpassword", "password");
 
      //save properties to project root folder
      prop.store(new FileOutputStream("config.properties"), null);
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
    }
}
 
package com.mkyong.common;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
 
public class App 
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file
      prop.load(new FileInputStream("config.properties"));
 
               //get the property value and print it out
                System.out.println(prop.getProperty("database"));
      System.out.println(prop.getProperty("dbuser"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
 
package com.mkyong.common;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.utilutil.Properties;
 
public class App 
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file from class path, inside static method
      prop.load(App.class.getClassLoader().getResourceAsStream("config.properties");));
 
               //get the property value and print it out
                System.out.println(prop.getProperty("database"));
      System.out.println(prop.getProperty("dbuser"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}