2

I am writing a java code that will append a path string to the %PATH% variable using java

In command prompt the command is

setx PATH "%PATH%;C:\my Path\"

In java here is my code:

import java.io.File;
import java.io.IOException;

public class AddToPATHVariable {
    public static void main(String[] args) throws InterruptedException, IOException {
        String folderPath = "C:\\my Path\\";
        System.out.println(folderPath);
        Runtime rt = Runtime.getRuntime() ;
        Process p = rt.exec("setx PATH \"%PATH%;" + folderPath + "\"");
        p.waitFor();
        p.destroy();
    }

}

The issue is that my command line prompt is append the new string perfectly. But java code is make the value to path variable to be %PATH%;C:\my Path\

someone please guide me in this regard.

Javeria Habib
  • 467
  • 2
  • 6
  • 15

1 Answers1

2

Well, as nothing is in charge of converting %PATH% it simply is not converted !

More seriously, it is the cmd.exe interpretor that actually does the translation of environment variables and you do not use it. To have it to work, you must :

  1. convert the environment variable PATH to its value in java code

    String path = System.getenv("PATH");
    
  2. use the converted String in your command

    Process p = rt.exec("setx PATH \"" + path + ";" + folderPath + "\"");
    

EDIT :

To really be sure of what happens, you can display the generated command before executing it :

String cmd = "setx PATH \"" + path + ";" + folderPath + "\"";
Process p = rt.exec(cmd);
Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199
  • I do the same...and even have debugged it but in the end result, it appends some part from the start of the original path instead of the folderpath. – Javeria Habib Aug 15 '14 at 06:15
  • getenv is returning the PATH variable 3 times – Javeria Habib Aug 15 '14 at 07:23
  • @JaveriaHabib I updated my anwser to be sure of the executed command. But beware : setx modify the environment for **futures** windows command, not for current one. Look at `setx /?` it should say something like : *in an local system, variables created or changed by this tool will be used by future command windows, but not in current CMD.EXE window* (translation is mine, my system speaks french :-) ) – Serge Ballesta Aug 15 '14 at 08:20