14

I am trying to set the PATH environment variable for the process builder in java, I tried the following:

ProcessBuilder pb = new ProcessBuilder(command);
Map<String, String> mp = pb.environment();
mp.put("Path", "myPath");
pb.start();

But the following did not work, the process builder picked the default system path. I came across this question and this trick his not helping me in my current project. What should I do to get around this?

Community
  • 1
  • 1
Destructor
  • 3,154
  • 7
  • 32
  • 51
  • Can you print all environment map values? It can be just case problem - PATH – kingoleg Nov 18 '14 at 13:10
  • The MAP has PATH and Path variables set. I saw the answer by Mike Clark in the same link above and I am wondering if what he has mentioned is correct behaviour . If it is then I am at loss. – Destructor Nov 18 '14 at 13:19
  • What do you mean "did not work"? I've just checked and it works for me. – kingoleg Nov 18 '14 at 15:53
  • I had an executable mystuff.exe in C:\mystuff and this was not in PATH variable, so I added this to PATH variable and tried using ProcessBuilder with command as just: mystuff.exe , even though PATH was set it complained that mystuff.exe file not found. So I had to resort to using full path instead of just mystuff.exe. – Destructor Nov 18 '14 at 17:14
  • 2
    I think that pb.environment() set env variables for a proccess, but it doesn't use Path from it to find your comment in constructor. – kingoleg Nov 19 '14 at 14:41
  • That was the problem! thanks.. – Destructor Nov 19 '14 at 15:26

1 Answers1

15

Path is used in a new proccess. It doesn't used to find your command.

You can try the next solution. Run cmd.exe (bash etc.) and then run your command.

Example:

public class Test {

    public static void main(String[] args) throws IOException {
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start", "mystuff.exe");
        Map<String, String> envs = pb.environment();
        System.out.println(envs.get("Path"));
        envs.put("Path", "C:\\mystuff");
        pb.redirectErrorStream();
        pb.start();

    }

}
kingoleg
  • 1,305
  • 15
  • 24