jayeshcp
1/7/2015 - 3:35 PM

Reading .properties file

Reading .properties file

# App Properties
name=Demo App
author=Jayesh
email=jaycp@gmail.com
/**
 *  This program reads config.properties file and displays
 *  all the keys and values
 *
 *  @author Jayesh Chandrapal
 *  @version 1.0
 */
 
import java.util.Properties;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

public class ReadProperties {
  public static void main(String[] args) {
    Properties prop;
    
    try {
      
      prop = new AppProperties().getProps();
      
      // Print properties value by key
      System.out.println(prop.getProperty("name"));
      System.out.println(prop.getProperty("author"));
      System.out.println(prop.getProperty("email"));
      
      // Print properties by iterating through all keys
      String key;
      Set<String> keys = prop.stringPropertyNames();
      Iterator<String> iter = keys.iterator();
      
      while(iter.hasNext()) {
        key = iter.next();
        System.out.println( key + "=" + prop.getProperty(key) );
      }
      
      // Can also print all properties like this
      prop.list( System.out );
      
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
}
 
class AppProperties {
  
  public Properties getProps() throws IOException {
    
    Properties prop = new Properties();
    String propFileName = "config.properties";
    InputStream inputStream = new FileInputStream(propFileName);
 
    if (inputStream != null) {
      prop.load(inputStream);
    } else {
      throw new FileNotFoundException("Property file '" + propFileName + "' not found in the classpath");
    }
    
    return prop;
  }
  
}