Read Properties File Java

Read Properties File Java

Any project you work you will need property file to keep constant data in it and read dynamically inside your program. Here you will see how to read property file using java:

  • Sample java project structure shown below where property file stored inside resource folder:

Read Properties File Java

  • Java program which will read data from property file:
package com.javahonk;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class ReadPropertyFileJava {

	public static void main(String[] args) {		
		
		InputStream input;
		try {
			
			Properties properties = new Properties();
			input = new FileInputStream("resources/JavaHonk.properties");
			properties.load(input);
			
			//Read single value
			System.out.println("Key: Name  Value: "+properties.getProperty("Name")+"\n");
			
			//Print value from property file
			Enumeration<?> enumeration =properties.propertyNames();
			while (enumeration.hasMoreElements()) {
				String key = (String) enumeration.nextElement();
				System.out.println("Key: "+key+"   Value: "+properties.getProperty(key));				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
  • Output:

Read Properties File Java

  •  For more information about Java Properties please see oracle documentation here 

Leave a Reply

Your email address will not be published. Required fields are marked *