How to Detect the Username Using Java

1. Overview

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.

2. System.getProperty

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.

3. System.getenv

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.

4. Conclusion

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.

       

\"IT電腦補習
立刻註冊及報名電腦補習課程吧!

Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses

Email:
public1989two@gmail.com






www.itsec.hk
www.itsec.vip
www.itseceu.uk

Be the first to comment

Leave a Reply

Your email address will not be published.


*