1. Overview
1.概述
Sometimes, working with Java applications, we need to access the values of system properties and environment variables.
有时,在使用 Java 应用程序时,我们需要访问系统属性和环境变量的值。
In this tutorial, we’ll learn how to retrieve the user name from a running Java application.
在本教程中,我们将学习如何从运行中的 Java 应用程序中获取用户名。
2. System.getProperty
2.系统.获取属性</em
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:
我们可以使用 System.getProperty(String) 来获取用户信息,更准确地说,是用户名。该方法需要键值。通常,它们是统一和预定义的,例如 java.version, os.name, user.home 等。在我们的例子中,我们感兴趣的是 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.
该方法的重载版本 System 可以防止我们使用不存在的属性.getProperty(String, String),该方法使用默认值。
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:
除了使用预定义的系统属性外,该方法还允许我们获取使用 -D 前缀传递的自定义属性的值。如果我们使用以下命令运行应用程序:
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.
此外,还可以使用 System.setProperty,但更改关键属性可能会对系统产生不可预知的影响。
3. System.getenv
3. System.getenv
Additionally, we can use environment variables to get a user name. Usually, it can be found by either USERNAME or USER:
此外,我们还可以使用环境变量来获取用户名。通常,可以通过 USERNAME 或 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
4.结论
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.
与往常一样,所有示例均可在 GitHub 上获取。