3

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.

3
  • are you talking about double backslash (\\ ) converting to Single backslash? Commented Aug 8, 2014 at 11:25
  • @NutterzUK I mean the the previous path value is replace my hardcoded string %PATH% Commented Aug 8, 2014 at 11:49
  • @Orion...no, I mean the the previous path value is replace my hardcoded string %PATH% Commented Aug 8, 2014 at 11:49

1 Answer 1

3

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
getenv is returning the PATH variable 3 times
@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 :-) )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.