Java ProcessBuilder: environment set correctly but still command not found

限于喜欢 提交于 2019-12-02 03:27:48

问题


I am having troubles with Java's ProcessBuilder on an Eclipse plugin I'm developing. I correctly set the environment before calling the start() method, but when I run the program, it always returns a command not found error.

When I call the command via command line it works perfectly.

When I start the eclipse with the environment as I require, the command is found and the program works fine.

Only when I set the environment programatically, the program fails.

Here is what I have:

ProcessBuilder pb = new ProcessBuilder("my_command", file, output);
Map<String, String> env = pb.environment();
env.put("PATH", env.get("PATH") + File.pathSeparator + env1 + File.pathSeparator + env2);
Process p = pb.start();
...

where, env1 and env2 are the paths I want to add to the PATH variable...

What is wrong in this code?

Thank you in advance!


回答1:


I think, the environment you set on the ProcessBuilder is only what is passed to the new process but not what is used by the builder itself. Try setting the environment variables of your Java process before trying to start the new process.

Edit:

Seeing that it may not be possible to alter the Java process's environment, I believe you have to come up with some work-around.

When you already know the path(s) you are looking for you can of course figure out the full path to "my_command" yourself, about so:

String commandString;

if ( new File(env1 + "/my_command").isFile() ) {
  commandString = env1 + "/my_command";
} else
if ( new File(env2 + "/my_command").isFile() ) {
  commandString = env2 + "/my_command";
}

ProcessBuilder pb = new ProcessBuilder(commandString, file, output);

Might be impractical though, if "my_command" may already be in one of the user's PATH elements.



来源:https://stackoverflow.com/questions/23153277/java-processbuilder-environment-set-correctly-but-still-command-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!