How to Read Property File in Static Context in Java


Here we can obtain the methods to read a property in a static code block. First stating that a static properties member loads the property information in a static code block, and then obtaining the property in a test class.

Source Code

package com.beginner.examples;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;



public class ReadPropertyInStaticContext {

	public static Properties pro;

	//Static blocks of code are executed as soon as the class is loaded
	//Then pro will have a value
	static {
		try {
			//Get the input stream from the file
			InputStream is = new FileInputStream("colors.properties");

			pro = new Properties();
			//Load it into pro
			pro.load(is);
			
			is.close();

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}

class Test {

	public static void main(String[] args) {
		
		//gets the property from the above class
		Properties pro = ReadPropertyInStaticContext.pro;
		
		//get the collection of relational objects
		Set<Map.Entry> entries = pro.entrySet();

		for (Map.Entry entry : entries) {
			//get the key
			String key = (String) entry.getKey();
			//get the value
			String value = (String) entry.getValue();

			System.out.println(key + " : " + value);

		}

	}

}

Output:

color_4 : black	
color_1 : red
color_2 : green
color_3 : yellow

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments