Java user name environment

Java user name environment

Много операционных систем используют переменные окружения, чтобы передать конфигурационную информацию к приложениям. Как свойства в платформе Java, переменные окружения являются парами ключ/значение, где и ключ и значение являются строками. Соглашения для установки и использования переменных окружения изменяются между операционными системами, и также между интерпретаторами командной строки. Чтобы изучить, как передать переменные окружения к приложениям на Вашей системе, сошлитесь на свою системную документацию.

Запросы Переменных окружения

На платформе Java приложение использует System.getenv получать значения переменной окружения. Без параметра, getenv возвращает экземпляр только для чтения java.util.Map , где ключи карты являются именами переменной окружения, и значения карты являются значениями переменной окружения. Это демонстрируется в EnvMap пример:

import java.util.Map; public class EnvMap < public static void main (String[] args) < Mapenv = System.getenv(); for (String envName : env.keySet()) < System.out.format("%s=%s%n", envName, env.get(envName)); >> >

С a String параметр, getenv возвращает значение указанной переменной. Если переменная не определяется, getenv возвраты null . Env использование в качестве примера getenv этот способ запросить определенные переменные окружения, определенные на командной строке:

Читайте также:  How to unicode html

Передача Переменных окружения к Новым Процессам

Когда приложение Java использует a ProcessBuilder объект создать новый процесс, набор значения по умолчанию переменных окружения, которые передают к новому процессу, является тем же самым набором, обеспеченным для процесса виртуальной машины приложения. Приложение может изменить это использование набора ProcessBuilder.environment .

Проблемы Зависимости от платформы

Есть много тонких различий между способом, которым переменные окружения реализуются на различных системах. Например, Windows игнорирует регистр на имена переменной окружения, в то время как UNIX не делает. Путем переменные окружения используются, также изменяется. Например, Windows обеспечивает имя пользователя в вызванной переменной окружения USERNAME , в то время как реализации UNIX могли бы обеспечить имя пользователя в USER , LOGNAME , или оба.

Чтобы максимизировать мобильность, никогда не обращайтесь к переменной окружения, когда то же самое значение доступно в системном свойстве. Например, если операционная система обеспечит имя пользователя, то это всегда будет доступно в системном свойстве user.name .

Ваше использование этой страницы и всего материала на страницах под «Учебным баннером» Java подвергается этим официальным уведомлениям.

Авторское право © 1995, 2012 Oracle и/или его филиалы. Все права защищены.

Источник

How to Get Environment Variable in Java?

Java Course - Mastering the Fundamentals

The very common way of getting the Environment variable in Java is by using the System class. The system class provides a method name System.getenv() , which takes an optional String argument and can be used to get the value of an environment variable set in the current system.

The System.getEnv() method is an overloaded method API that returns a String map that contains all the environment variables and their values. We can give a String argument to get the value of the particular value as follows:

The variable has a key-value pair and on passing a key to the System.getEnv() method returns the value of the environment variable.

Another method of getting Environment Variable in Java is by using System Properties. But they have only a limited set of predefined environment variables like java.classpath, java.username, etc.

What is Environment Variable in Java?

An environment variable is a dynamic value used by the operating system and other applications to identify information related to a particular machine. An environment variable is a key value pair. Environment variable values are set outside the program, usually by the operating system through inbuilt functionality.

Various Examples to Get Environment Variables in Java

Let us see a few examples to understand how to get Environment the variable in Java:

Example 1: Getting specific environment variable

The above syntax can be used to store the value of the environment variable in a String for later use. To get the value of the specific variable a String argument is passed.

Let us now see an example to print the classpath for the java program.

The above example returns values for two variables Class Path and OS.

Example 2: Printing all the Environment Variables

Let us take another example to display all the environment variables of the system.

It returns a map of key-value pairs both being of String type. We can store it in the map for later use. Here we do not pass the String argument.

As we can see, all the variables are listed. As the optional argument String isn’t passed, the System.getenv() method returns a map having key-value pair both of type string. This map contains all the variables present. We are printing them using the System.out.format method to format the output.

Example 3: Getting Environment Variables using System Property

Another method of getting environment variables is using System Property.

It is similar to System.getenv() method. The System.getProperty() has values for only selected properties/variable.

Let us use various properties in an example using the System Property of the System class.

If no such property exists then the system returns null as in the case of home and name. The System.getProperty returns the properties of the specified fields.

Note: Similarly, we can also fetch various properties altogether using System.getProperties .

Learn More

If you found this interesting, you may also like to learn about Java IO Streams

Conclusion

  • To get environment variables we can use either System.getenv() or System.getProperty() methods of the System class.
  • Environment variables are key-value pairs storing system information for the machine used by the operating system and other applications.
  • Methods System.getenv() and System.getProperty() can be used to fetch values of a particular property as well as the list of all the properties.

Источник

How to get Environment Variables in Java — Example Tutorial

There are two ways to get the environment variable in Java, by using System properties or by using System.getEnv(). System properties provide only a limited set of predefined environment variables like java.classpath , for retrieving Java Classpath or java.username to get User Id which is used to run Java program, etc but a more robust and platform-independent way of getting environment variable in Java program o n the other hand System.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if the program relies on a particular environment variable.

The System.getEnv() is an overloaded method in Java API and if invoked without a parameter it returns an unmodifiable String map that contains all environment variables and their values available to this Java process while System.getEnv(String name) returns the value of the environment variable if exists or is null.

In our earlier posts, we have seen How to get the current directory in Java and How to run shell commands from the Java program, and in this Java tutorial, we will see how to access environment variables in Java.

How to get environment variables in Java — Example

Here is a quick example of How to get environment variables in Java using System.getEnv() and System.getProperty() . Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return the value of a named environment variable like JAVA_HOME will return PATH of your JDK installation directory.

/**
* Java program to demonstrate How to get the value of environment variables in Java.
* Don’t confuse between System property and Environment variable and there is separate
* way to get the value of System property than environment variable in Java, as shown in this
* example.
*
* @author Javin Paul
*/

public class EnvironmentVariableDemo

public static void main ( String args [])

//getting username using System.getProperty in Java
String user = System. getProperty ( «user.name» ) ;
System. out . println ( «Username using system property: » + user ) ;

//getting username as an environment variable in java only works in windows
String userWindows = System. getenv ( «USERNAME» ) ;
System. out . println ( «Username using environment variable in windows : » + userWindows ) ;

//name and value of all environment variables in Java program
Map < String, String > env = System. getenv () ;
for ( String envName : env. keySet ()) <
System. out . format ( «%s=%s%n» , envName, env. get ( envName )) ;
>

Output:
Username using system property: harry
Username using environment variable in windows: harry
USERPROFILE=C:\Documents and Settings\harry
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_20\
TEMP=C:\DOCUME~ 1 \harry\LOCALS~ 1 \Temp

Getting environment variable in Java – Things to remember

Java is a platform-independent language but there are many things that can make a Java program platform-dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be a bit careful while directly accessing environment variables inside the Java program. Here are few points which are worth noting :

1) U se system properties if the value of environment variable is available via system property e .g. Username which is available using » user.name » system property. If you access it using environment variable directly you may need to ask for different variables as it may be different in Windows e.g. USERNAME and Unix as USER .

2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.

3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.

That’s all on how to get the environment variable in Java. Though you have a convenient method like System.getEnv() which can return the value of the environment variable, its better to use System.getProperty() to get that value in a platform-independent way if that environment variable is available as a system property in Java.

Источник

Environment Variables

Many operating systems use environment variables to pass configuration information to applications. Like properties in the Java platform, environment variables are key/value pairs, where both the key and the value are strings. The conventions for setting and using environment variables vary between operating systems, and also between command line interpreters. To learn how to pass environment variables to applications on your system, refer to your system documentation.

Querying Environment Variables

On the Java platform, an application uses System.getenv to retrieve environment variable values. Without an argument, getenv returns a read-only instance of java.util.Map , where the map keys are the environment variable names, and the map values are the environment variable values. This is demonstrated in the EnvMap example:

import java.util.Map; public class EnvMap < public static void main (String[] args) < Mapenv = System.getenv(); for (String envName : env.keySet()) < System.out.format("%s=%s%n", envName, env.get(envName)); >> >

With a String argument, getenv returns the value of the specified variable. If the variable is not defined, getenv returns null . The Env example uses getenv this way to query specific environment variables, specified on the command line:

Passing Environment Variables to New Processes

When a Java application uses a ProcessBuilder object to create a new process, the default set of environment variables passed to the new process is the same set provided to the application’s virtual machine process. The application can change this set using ProcessBuilder.environment .

Platform Dependency Issues

There are many subtle differences between the way environment variables are implemented on different systems. For example, Windows ignores case in environment variable names, while UNIX does not. The way environment variables are used also varies. For example, Windows provides the user name in an environment variable called USERNAME , while UNIX implementations might provide the user name in USER , LOGNAME , or both.

To maximize portability, never refer to an environment variable when the same value is available in a system property. For example, if the operating system provides a user name, it will always be available in the system property user.name .

Источник

Оцените статью