0

I need to add a new directory to the PATH environment variable in Java. I have used below code but it seems to launch a command shell and hangs which i don't want.

Is there an easy way to update the PATH environment variable from within JAVA code?

try {
    Process proc = Runtime.getRuntime().exec("cmd set PATH=%PATH%;C:\\MyDir1");
    proc.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    String line = reader.readLine();
    while (line != null) {
        //Handle what you want it to do here
        line = reader.readLine();
    }
}
catch (IOException | InterruptedException e1) {
    //Handle your exception here
}
Helena
  • 444
  • 2
  • 15
  • 1
    Does this answer your question? [How to update system PATH variable permanently from cmd?](https://stackoverflow.com/questions/24219627/how-to-update-system-path-variable-permanently-from-cmd) – sorifiend Jun 23 '22 at 04:14
  • 1
    Does this answer your question? [How do I set environment variables from Java?](https://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java) – Sayan Bhattacharya Jun 23 '22 at 04:15

1 Answers1

0

You will need to use ProcessBuilder class to create environment variables. Something like this

ProcessBuilder builder = new ProcessBuilder();
Map<String, String> environment = processBuilder.environment();
environment.put("JAVA_PATH", "mypath");
processBuilder.command("cmd.exe", "/c", "set PATH=%;%JAVA_PATH%");
Vivek Raut
  • 49
  • 3