Wednesday 17 November 2021

Java: Set a system property in command line

Using -Dproperty=value syntax, we can set a system property value. If the value is a string that contains spaces, you must enclose the string in double-quotes.

SystemPropertiesDemo1.java
public class SystemPropertiesDemo1 {

	public static void main(String args[]) {
		String appName = System.getProperty("appName");
		String appVersion = System.getProperty("appVersion");

		System.out.println("appName -> " + appName);
		System.out.println("appVersion -> " + appVersion);
	}

}

Run the above application by passing the system properties using -Dproperty=value syntax like below.

java -DappName="Chat Server" -DappVersion=1.23 SystemPropertiesDemo1



You can see the system properties printed in console.

 

How to read all system properties?

Using System.getProperties() method, you can get all the current system properties.

 

SystemPropertiesDemo.java

package com.sample.app.system;

import java.util.Properties;
import java.util.Set;

public class SystemPropertiesDemo {

	public static void main(String args[]) {
		Properties properties = System.getProperties();

		Set<Object> propertiesSet = properties.keySet();

		for (Object property : propertiesSet) {
			System.out.println(property + " -> " + properties.getProperty(property.toString()));
		}
	}

}

How to read a specific system property?

'java.lang.System' class provides 'getProperty' method to read the system properties.

 

public static String getProperty(String key)

Gets the system property indicated by the specified key. Return null, if there is no property with that key.

 

public static String getProperty(String key, String defaultValue)

Gets the system property indicated by the specified key. Return the default value if there is no property with that key.

 

 

Reference

https://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html



You may like

Interview Questions

Java: Get the index of last occurrence of a substring

Java: Get all the indexes of occurrence of a substring

Java: How to replace a value in ArrayList or LinkedList

Why do we declare logger with static and final?

How to check the type of a variable in Java?

No comments:

Post a Comment