Eugene S Eugene S - 3 years ago 123
Java Question

How to overwrite values loaded from properties file if new value is provided in command line

Funny enough there are 2 almost identical questions with a similar title that I found:



however my case seems to be slightly different.

So I have a
file that is being loaded by
class like this:

public class ConfigurationGetter {

Properties prop = new Properties();
InputStream inputStream = null;

public Properties getPropValues() throws IOException {

try {
String fileName = "";

inputStream = getClass().getClassLoader().getResourceAsStream(fileName);

if (inputStream != null) {
} else {
throw new FileNotFoundException("property file '" + fileName + "' not found in the classpath");

} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {

return prop;


Then I instantiate this class in another class like this:

ConfigurationGetter config = new ConfigurationGetter();
props = config.getPropValues();

And then I can extract the properties by key like this:


Whet I want to do is to overwrite this value I get from properties file if I provide it via command line. For example, if I have a line like this in my
that I loaded as explained above:


and I also run the code like this:

mvn test -DkeyName=false

will be the one resolved.

Answer Source

After loading the properties file, I do the following:

for (String propertyName : properties.stringPropertyNames()) {
    String systemPropertyValue = System.getProperty(propertyName);

    if (systemPropertyValue != null) {
        properties.setProperty(propertyName, systemPropertyValue);

This gives you the behavior you want by overriding the value from the property file with the corresponding system property value if it is present.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download