0

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);  

     Map<String,String> env = 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);  
     }  
}

But after execution , the envorinment variable is not set in "PATH" varaible . Why ?

August
  • 10,796
  • 2
  • 30
  • 47
osimer pothe
  • 2,667
  • 13
  • 45
  • 91
  • What are you getting in this? – Pratik Butani Dec 26 '14 at 06:55
  • 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. – Henry Dec 26 '14 at 06:59
  • To do this, you're going to have get your hands dirty at the native level via JNI/JNA – MadProgrammer Dec 26 '14 at 07:01
  • possible dup of http://stackoverflow.com/questions/2741175/set-windows-path-environment-variable-at-runtime-in-java – wgitscht Dec 26 '14 at 07:02
  • 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? – Christian Hujer Dec 26 '14 at 07:31

2 Answers2

4

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.

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.

Christian Hujer
  • 14,160
  • 5
  • 30
  • 40
2

Simple example for how to set path with setx.exe in command line:

setx path "jdk bin path"

ex

setx path "C:\Program Files (x86)\Java\jdk1.7.0_04\bin"

try this on your code

like

    try {

        // using the Runtime exec method:
        Process p = Runtime.getRuntime().exec("setx path C:\Program Files (x86)\Java\jdk1.7.0_04\bin");

        BufferedReader stdInput = new BufferedReader(new
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
             InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }

        System.exit(0);
    }
    catch (IOException e) {
        System.out.println("exception happened - here's what I know: ");
        e.printStackTrace();
        System.exit(-1);
    }
Elango
  • 391
  • 2
  • 21
  • i have explained more clear here: http://stackoverflow.com/questions/1672281/environment-variables-for-java-installation/31340459#31340459 – hitesh141 Jul 10 '15 at 12:11