How to Read Properties File From a Static Block in Java


In this example, we may get the method to load properties file from a static block.

Source Code

package com.beginner.examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LoadPropertiesFileFromStaticBlock {
	private static Properties properties;
	
	/*
	 * Use FileInputStream to load the properties file
	 * from classpath within static block. 
	 */
	static {
		try {
			properties = new Properties();
			File file = new File("tmp.properties");
			InputStream inputStream = new FileInputStream(file);
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getPropertyValue(String key){
		return properties.getProperty(key);
	}
	
	public static void main(String[] args) {
		System.out.println("db.username: " + properties.getProperty("db.username"));
		System.out.println("db.userage: " + properties.getProperty("db.userage"));
	}

}

tmp.properties

db.username = Alice
db.userage = 17

Output:

db.username: Alice
db.userage: 17

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments