Set environment variable using java

How to set environment variable in java [duplicate]

I want to set environment variable in JAVA . For this , I have searched a lot in internet and got the following code .

void set_up_environment_var() throws IOException < ProcessBuilder pb = new ProcessBuilder("CMD.exe", "/C", "SET"); // SET prints out the environment variables pb.redirectErrorStream(true); Mapenv = pb.environment(); String str1 = ";C:\\naved\\bin"; String path = env.get("Path") ;//+ ";C:\\naved\\bin"; System.out.println("ok , I am coming . "+path.toLowerCase().contains(str1.toLowerCase())); env.put("Path", path.concat(str1)); Process process = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = in.readLine()) != null) < // System.out.println(line); >> 

The environment in the OS is not a global space, it is local to the executing process. When a process starts another one the environment of the new process is inherited from the parent. You can never change the environment of the parent from a subprocess.

It’s not entirely clear what you’re asking. For example, ‘the environment variable is not set in «PATH» variable.’ The PATH variable is an environment variable, so your question sounds a bit confused. What exactly do you want to achieve?

2 Answers 2

A process can only set environment variables of itself and for processes it will spawn in future. A process cannot set the environment variables of already running processes.

You might have already noticed that when you were setting environment variables manually, globally in the system. They will not affect instances of processes which are already running, like an already running cmd.exe or an already running bash . You might also have noticed, that if you set an environment variable that way, that whether or not a new process gets the new environment variable setting depends on how the new process is started. The default behavior is that a process is started with a copy of the environment of its parent process, which is the process that starts the new process.

As a simple explanation, you could say there are root processes and child processes. root processes get the environment settings from the global settings, child processes inherit the environment settings from their parent processes.

Читайте также:  Java io tmp directory

The question is what do you want to achieve with setting the environment? I could think of at least three different things that you could want to achieve:

  • Set the environment globally, as part of an installer.
  • Set the environment for the currently running JVM.
  • Set the environment for a process that you will be starting.
  • Set the environment for the calling process directly (not possible!).
  • Set the environment for the calling process indirectly.

Setting the environment globally, as part of an installer

This is highly system-specific. On UNIX, this topic is actually avoided. Programs would rather provide wrapper scripts that set the environment instead of setting global environment variables. The philosophy in UNIX is that usually environment variables are only used in cases where the variable would be useful for more than just one process. Examples for such varaibles are PATH and EDITOR .

On Windows, you would probably call regedit to modify the environment.

Setting the environment of the currently running JVM

There is no API for setting the environment of the currently running JVM, so you would have to use JNI for this. However, be advised, that the fact that there is no API for this is for good reasons, and part of these reasons might be that the JVM doesn’t want its environment be arbitrarily changed by some Java code.

Setting the environment for a process that will be started

When you start a process using one of the Runtime.exec() methods, you can actually provide the environment that you like.

If you want to start a process with a modified environment, the best way would be to use ProcessBuilder . It provides a method environment() for modifying the environment for the new process.

Setting the environment for the calling process directly

If you want to implement the set command in Java, forget it, it is not possible. set is not a program, it’s an internal command of the shell, i.e. cmd.exe . Because of the explanation above, it wouldn’t work otherwise.

Setting the environment for the calling process indirectly

You can set the environment for the calling process indirectly — if the calling process cooperates. If your calling process is cmd.exe or sh , you could have your Java program generate a temporary batch file or shell script, and then have the calling cmd.exe or sh execute that batch file or shell script.

Читайте также:  Javascript add to dict

Источник

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.

Читайте также:  Python работа со справочниками

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() .

Источник

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