How to Assign Default Values in Properties File in Java


In this example we will show the method to assign default values for unavailable keys in properties file.

Source Code

package com.beginner.examples;

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

public class AssignDefaultValuesInPropertiesFile {
	
	private static Properties properties = null;
	
	public AssignDefaultValuesInPropertiesFile(){
		
		try {
			properties = new Properties();
			File file = new File("tmp.properties");
			InputStream inputStream = new FileInputStream(file);
			properties.load(inputStream);
		}catch (IOException io) {
			io.printStackTrace();
		}
	}
	
    	public String getPropertyValue(String key){
    		/*
    	 	* Specify the default value.
    	 	*/
        	return properties.getProperty(key, "Default Value");
    	}
    
	public static void main(String[] args) {
		
		AssignDefaultValuesInPropertiesFile advp = new AssignDefaultValuesInPropertiesFile();
		System.out.println("db.username: " + advp.getPropertyValue("db.username"));
		System.out.println("db.userage: " + advp.getPropertyValue("db.userage"));
		System.out.println("db.userage: " + advp.getPropertyValue("db.x"));
		
	}

}

tmp.properties

db.username = Alice
db.userage = 17

Output:

db.username: Alice
db.userage: 17
db.userage: Default Value

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments