Load Property Configuration File
Sometimes while working on java application you want to load property from configuration file. In this sample java program you will see how to load and read property from configuration file:
- Sample project where we will read property value form src\main\resources\config.properties file, sets to system property and print its value to the console:
- config.properties file:
- LoadPropertyFileJava.java:
package com.javahonk; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Map; import java.util.Properties; public class LoadPropertyFile { public static void main(String[] args) throws Exception { //Example 1 Properties p = new Properties(); Reader myReader = new InputStreamReader(new FileInputStream("src\\main\\resources\\config.properties")); p.load(myReader); System.out.println("Example 1"); for (String name : p.stringPropertyNames()) { String value = p.getProperty(name); System.out.println("Key:" + name + "--> Value: " + value); System.setProperty(name, value); } //Example 2 Properties properties = new Properties(); StringBuilder builder = new StringBuilder(); InputStream inputStream = null; System.out.println("Example 2"); try { inputStream = new FileInputStream("src\\main\\resources\\config.properties"); properties.load(inputStream); for (Map.Entry entry : properties.entrySet()) { System.out.println("Key:" + entry.getKey() + "--> Value: " + entry.getValue()); System.setProperty(entry.getKey().toString(), entry.getValue().toString()); } } catch (Exception e1) { e1.printStackTrace(); }finally{ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(builder.toString()); } }
- Output:
- For more details please refer Oracle documentation here