Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run setx command using java [duplicate]

Tags:

java

path

setx

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.

like image 808
Javeria Habib Avatar asked May 26 '26 17:05

Javeria Habib


1 Answers

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);
like image 90
Serge Ballesta Avatar answered May 28 '26 05:05

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!