Sometimes, working with Java applications, we need to access the values of system properties and environment variables.
In this tutorial, we’ll learn how to retrieve the user name from a running Java application.
One way to get information about the user, more precisely, its name, we can use the System.getProperty(String). This method takes the key. Usually, they’re uniform and predefined, such as java.version, os.name, user.home, etc. In our case, we’re interested in the user.name:
String username = System.getProperty("user.name"); System.out.println("User: " + username);
An overloaded version of this method System can protect us from non-existent properties.getProperty(String, String), which takes a default value.
String customProperty = System.getProperty("non-existent-property", "default value"); System.out.println("Custom property: " + customProperty);
Aside from working with predefined system properties, this method allows us to get the values of the custom properties we’ve passed with the -D prefix. If we run our application with the following command:
java -jar app.jar -Dcustom.prop=`Hello World!`
Inside an application, we can use this value
String customProperty = System.getProperty("custom.prop"); System.out.println("Custom property: " + customProperty);
This can help us make flexible and extensible codebase by passing values at the startup.
Additionally, it’s possible to use System.setProperty, but changing crucial properties might have unpredictable effects on the system.
Additionally, we can use environment variables to get a user name. Usually, it can be found by either USERNAME or USER:
String username = System.getenv("USERNAME"); System.out.println("User: " + username);
The environment variables are read-only but also provide an excellent mechanism to get information about the system the application runs in.
In this article, we discussed a couple of ways to get the required information about the environment. Environment variables and properties are a convenient way to gain more information about the system. Also, they allow custom variables to make an application more flexible.
As usual, all the examples are available over on GitHub.