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 test.properties,

blogSite=improveJava
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 test.properties is placed
        //in root directory of project
		try {
			InputStream fileInputStream = new FileInputStream("test.properties");
			properties.load(fileInputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String post = properties.getProperty("post");
		System.out.println(post);
		
		String xyz = properties.getProperty("xyz");
		System.out.println(xyz);
		
		Object xyzOrDefault = properties.getOrDefault("xyz", "XYZ Default Value");
		System.out.println(xyzOrDefault.toString());
	}

}

Above program produces following output,

Read Properties
null
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:

WordPress.com Logo

You are commenting using your WordPress.com 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