Read Properties

Properties files are one of the key things used in projects to store essential informations i.e. database related properties which can be easily changed later without changing anything in the Java code.

So, following is an example of properties file named,

post=Read Properties

In properties file every property has a key and a value, in above properties file ‘post’ is a key and ‘Read Properties file’ is value. By convention we should always start key of properties file with lower case.

We have to use java.util.Properties to load, read or write properties to the properties file.

Consider following example,

public class ReadPropertiesFile {

	public static void main(String[] args) {
		Properties properties = new Properties();
		//Currently is placed
        //in root directory of project
		try {
			InputStream fileInputStream = new FileInputStream("");
		} catch (IOException e) {
		String post = properties.getProperty("post");
		String xyz = properties.getProperty("xyz");
		Object xyzOrDefault = properties.getOrDefault("xyz", "XYZ Default Value");


Above program produces following output,

Read Properties
XYZ Default Value

Note that to read properties file we first have to load them from the input stream.

You can also load properties from XML file or from FileReader as well. But worth to mention that Properties are processed in terms of lines.

In above program we got null because our properties file does not have any property with key ‘xyz’ if you want to avoid the null value you can use getOrDefault which can return default values if the specified key is not available in properties file instead of null.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s