Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, 10 February 2017

How to read values from configuration properties file in java

How to read values from configuration properties file in java

For example, I will create 3 files.

1. main.properties file.properties is a file extension for files mainly used in Java related technologies to store the configurable parameters of an application. Each parameter is stored as a pair of strings, one storing the name of the parameter (called the key/map), and the other storing the value.

2. GetPropertyValues.java: This java file will have implementation to get property values from property file.

3. ReadConfigMain.java: This java file will have main method and will use to call method of GetPropertyValues class.

Step 1: Create main.properties file

1. If you have spring project, create main.properties file under src/main/resources. Else, create Folder “resources” under Java Resources folder if your project doesn’t have it and than create main.properties file under /Java Resources/resources/.

2. Create main.properties file as given below:

How to read values from properties file in java
main.propertis file content:

queue_name=QUEUE
queue_manager=QM
queue_hostname=localhost
queue_port=1414


Step 2: Create ReadConfigMain java class

package engineernitesh.blogspot.com;
import java.io.IOException;
public class ReadConfigMain {
public static void main(String[] args) throws IOException {
GetPropertyValues properties = new GetPropertyValues();
properties.getPropValues();
}
}

Step 3: Create GetPropertyValues java class

package engineernitesh.blogspot.com;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
public class GetPropertyValues {
String result = "";
InputStream inputStream;
public String getPropValues() throws IOException {
try {
Properties prop = new Properties();
String propFileName = "main.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String queue_name = prop.getProperty("queue_name");
String queue_manager = prop.getProperty("queue_manager");
String queue_hostname = prop.getProperty("queue_hostname");
String queue_port = prop.getProperty("queue_port");
result = queue_hostname+":" + queue_port + "\ " + queue_manager + "\ " + queue_name;
System.out.println("result: "+result);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
inputStream.close();
}
return result;
}
}