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.

       


电子产品 排行榜


Gurmandise 哆啦A梦 铜锣烧 手机手环

IT電腦補習 java補習 為大家配對電腦補習,IT freelance, 私人老師, PHP補習,CSS補習,XML,Java補習,MySQL補習,graphic design補習,中小學ICT補習,一對一私人補習和Freelance自由工作配對。
立刻註冊及報名電腦補習課程吧!

facebook 查詢:
24 hours enquiry facebook channel :
https://www.facebook.com/itteacheritfreelance/?ref=aymt_homepage_panel

Be the first to comment

Leave a Reply

Your email address will not be published.


*