先来看一下ProcessBuilder类这段DOC
* <blockquote><pre>
* Process p = new ProcessBuilder("myCommand", "myArg").start();
* </pre></blockquote>
*
* <p>Here is an example that starts a process with a modified working
* directory and environment:
*
* <blockquote><pre>
* ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
* Map<String, String> env = pb.environment();
* env.put("VAR1", "myValue");
* env.remove("OTHERVAR");
* env.put("VAR2", env.get("VAR1") + "suffix");
* pb.directory(new File("myDir"));
* Process p = pb.start();
* </pre></blockquote>
*
* <p>To start a process with an explicit set of environment
* variables, first call {@link java.util.Map#clear() Map.clear()}
* before adding environment variables.
*
* @since 1.5
*/
public final class ProcessBuilder
{
按这个例子改完之后怎么运行都报错:
Exception in thread "main" java.io.IOException: Cannot run program "ffmpeg.exe": CreateProcess error=2
at java.lang.ProcessBuilder.start(Unknown Source)
再看一下环境变量:
new ProcessBuilder().environment()
path根本没有改变!
google发现了这篇文章:
http://weblog.dangertree.net/2007/04/13/changing-path-and-environment-in-java-processbuilder/
引用
The first and most important issue is this: Changes to the Path environment variable are not reflected until a new process is created and running. Here is an example of how this can bite you in the ass:
ProcessBuilder pb =
new ProcessBuilder(”myExe.exe”, “arg1″, “arg2″);
Map env = pb.environment();
// watch out here! this could be “PATH” or “path”
// Windows doesn’t care, but Java will
String path = env.get(”Path”);
env.set(”Path”, path + File.pathSeparator
+ “path\to\the\executable”);
pb.start();
1.You have an executable file that you want to run with ProcessBuilder that is not on your path.
2.You assume that you can write the previous code in order to temporarily add the exe’s path to the process’s environment before executing it.
3.You always get an error=2 back from the ProcessBuilder because it cannot find the file.
This is because the changes you made to the new process environment are not reflected until the process is actually running. In other words, Java does not change the path until it attempts to execute the command you have told it to execute. It will never find an executable file that is not on the previous system path even if you change the “Path” environment variable in the ProcessBuilder before you call the “start()” method.
浪费了小半个下午的时间!