ProcessBuilder 和 Runtime.exec() 的区别 [英] Difference between ProcessBuilder and Runtime.exec()
问题描述
我正在尝试从 java 代码执行外部命令,但我注意到 Runtime.getRuntime().exec(...)
和 new ProcessBuilder 之间存在差异(...).start()
.
I'm trying to execute an external command from java code, but there's a difference I've noticed between Runtime.getRuntime().exec(...)
and new ProcessBuilder(...).start()
.
使用 Runtime
时:
Process p = Runtime.getRuntime().exec(installation_path +
uninstall_path +
uninstall_command +
uninstall_arguments);
p.waitFor();
exitValue 为 0,命令正常终止.
the exitValue is 0 and the command is terminated ok.
但是,使用 ProcessBuilder
:
Process p = (new ProcessBuilder(installation_path +
uninstall_path +
uninstall_command,
uninstall_arguments)).start();
p.waitFor();
退出值为 1001,命令在中间终止,尽管 waitFor
返回.
the exit value is 1001 and the command terminates in the middle, although waitFor
returns.
我应该怎么做才能解决 ProcessBuilder
的问题?
What should I do to fix the problem with ProcessBuilder
?
推荐答案
Runtime.getRuntime().exec(...)
的各种重载采用字符串数组或单个字符串.exec()
的单字符串重载会将字符串标记为参数数组,然后将字符串数组传递给一个接受字符串的 exec()
重载大批.另一方面,ProcessBuilder
构造函数只接受一个可变的字符串数组或一个 List
字符串,其中数组或列表中的每个字符串都被假定为一个单独的争论.无论哪种方式,获得的参数都会被组合成一个字符串,然后传递给操作系统以执行.
The various overloads of Runtime.getRuntime().exec(...)
take either an array of strings or a single string. The single-string overloads of exec()
will tokenise the string into an array of arguments, before passing the string array onto one of the exec()
overloads that takes a string array. The ProcessBuilder
constructors, on the other hand, only take a varargs array of strings or a List
of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.
例如,在 Windows 上,
So, for example, on Windows,
Runtime.getRuntime().exec("C:DoStuff.exe -arg1 -arg2");
将运行带有两个给定参数的 DoStuff.exe
程序.在这种情况下,命令行被标记并重新组合在一起.然而,
will run a DoStuff.exe
program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,
ProcessBuilder b = new ProcessBuilder("C:DoStuff.exe -arg1 -arg2");
将失败,除非 C:
中有一个名为 DoStuff.exe -arg1 -arg2
的程序.这是因为没有标记化:假设要运行的命令已经被标记化.相反,您应该使用
will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2
in C:
. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use
ProcessBuilder b = new ProcessBuilder("C:DoStuff.exe", "-arg1", "-arg2");
或者替代
List<String> params = java.util.Arrays.asList("C:DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
这篇关于ProcessBuilder 和 Runtime.exec() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!