How to read data from properties file /create a configuration file

Project structure in Eclipse: 







config.properties :

browser=chrome
domain=http://www.whiteboxtest.com
userName=amritupadhyay
password=jimmi



ConfigParser :

package util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;

public class ConfigParser {
public static String browser;
public static String domain;
public static String userName;
public static String password;

private static final Logger LOGGER = Logger.getLogger(ConfigParser.class.getName());

public static void readConfig() {
String current;
try {
current = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + current);
String currentDir = System.getProperty("user.dir");
LOGGER.info("Current dir using System:" + currentDir);
} catch (IOException e1) {
e1.printStackTrace();
}

Properties prop = new Properties();
String propFileName = "src/config/config.properties";

InputStream inputStream = null;
try {
inputStream = new FileInputStream(propFileName);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}

try {
prop.load(inputStream);
} catch (IOException e) {
LOGGER.info("property file '" + propFileName + "' not found in the classpath");
}

browser = prop.getProperty("browser");
domain = prop.getProperty("domain");
userName = prop.getProperty("userName");
password = prop.getProperty("password");
}

public static String getBrowser() {
if (browser == null) {
readConfig();
}
return browser;
}

public static String getDomain() {
if (domain == null) {
readConfig();
}
return domain;
}

public static String getUserNane() {
if (userName == null) {
readConfig();
}
return userName;
}

public static String gePassword() throws FileNotFoundException, IOException {
if (password == null) {
readConfig();
}
return password;
}
}



PrintPropertiesFileData :

package com.test;

import java.io.FileNotFoundException;
import java.io.IOException;

import util.ConfigParser;

public class PrintPropertiesFileData {

public static void getPropertiesFileData() throws FileNotFoundException, IOException {
String browser = ConfigParser.getBrowser();
String domain = ConfigParser.getDomain();
String userName = ConfigParser.getUserNane();
String password = ConfigParser.gePassword();

System.out.println("Browser is " + browser);
System.out.println("Domain is " + domain);
System.out.println("User Name is " + userName);
System.out.println("Password is " + password);

}

public static void main(String[] args) throws IOException {
getPropertiesFileData();
}
}





No comments:

About Me

My photo
Pune, Maharastra, India
You can reach me out at : jimmiamrit@gmail.com