Setting environment variables from java

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 examples while loop example

/**
* 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 .

Источник

How do I set environment variables from Java?

To a system property from Java, you can use the System.setProperty() method. However, keep in mind that this method only sets system properties, which are different from environment variables.

System properties are a set of key-value pairs that can be set at the Java Virtual Machine (JVM) level, and are used to configure the behavior of the JVM and Java applications. They are stored in the java.lang.System class, and can be accessed using the System.getProperty() method.

To set a system property from Java, you can use the System.setProperty() method, like this:

System.setProperty("propertyName", "propertyValue");
System.setProperty("java.io.tmpdir", "/tmp");

This will set the java.io.tmpdir system property to the value «/tmp» .

Environment variables, on the other hand, are system-wide variables that are set outside of the JVM and are used to configure the operating system and other programs. They can be accessed using the System.getenv() method.

To set an environment variable from Java, you will need to use a native method or a third-party library that allows you to set environment variables.

One way to set environment variables from Java is to use the ProcessBuilder class. The ProcessBuilder class allows you to start a new process with a modified environment, which inherits the current process’s environment and allows you to make changes to it. Here’s an example of how you can set an environment variable using ProcessBuilder:

import java.io.IOException; import java.util.Map; public class SetEnvironmentVariable < public static void main(String[] args) < try < // Create a new ProcessBuilder instance ProcessBuilder processBuilder = new ProcessBuilder(); // Get the environment variables from the ProcessBuilder instance Map environment = processBuilder.environment(); // Set a new environment variable environment.put("MY_ENV_VAR", "MyEnvironmentVariableValue"); // Run a command with the modified environment processBuilder.command("someCommand"); Process process = processBuilder.start(); process.waitFor(); > catch (IOException | InterruptedException e) < e.printStackTrace(); >> >

In this example, we first create a new ProcessBuilder instance. Then, we retrieve the environment variables from the ProcessBuilder by calling the environment() method. Next, we set a new environment variable by calling the put() method on the Map of environment variables. Finally, we run a command using the start() method, which launches a new process with the modified environment.

Please note that this approach sets the environment variable for the new process and its child processes, but not for the current JVM process. The new environment variable will not be accessible from the current JVM process using System.getenv() .

Источник

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