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.
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 :
convert the environment variable PATH to its value in java code
String path = System.getenv("PATH");
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With