[英]Command works in terminal, but not with Runtime.exec
I'm trying to run some commands from a Java application using Runtime.getRuntime().exec(command)
. 我正在尝试使用
Runtime.getRuntime().exec(command)
从Java应用程序运行一些命令。 However, certain commands that work from a command line tool like Terminal fail when executed like this. 但是,某些命令行工具(如终端)的命令在执行时会失败。
Example: 例:
private static final String COMMAND = "cp -n /home/me/Downloads/a.png /home/me/Downloads/b.png";
private static final String COMMAND_2 = "cp -n /home/me/Downloads/a.png /home/me/Downloads/b.png && cp -n /home/me/Downloads/a.png /home/me/Downloads/b.png";
public static void main(String[] args) throws Exception {
int result = Runtime.getRuntime().exec(COMMAND).waitFor();
System.out.println(result); // prints 0
int result2 = Runtime.getRuntime().exec(COMMAND_2).waitFor();
System.out.println(result2); // prints 1
}
Note that COMMAND_2
does the same as COMMAND
twice, separated by &&
. 请注意,
COMMAND_2
与COMMAND
相同两次,由&&
分隔。 Why does one succeed, but the other fail? 为什么一个成功,但另一个失败? Both work just fine in Terminal.
两个都在终端工作得很好。
I'm using Oracle-Java 1.7.0 on Red Hat Enterprise Linux 6. 我在Red Hat Enterprise Linux 6上使用Oracle-Java 1.7.0。
This is the most common mistake of all times when it comes to a Process
. 这是所有时代最常见的错误,当涉及到一个
Process
。
A process is not a shell interpreter . 进程不是shell解释器 。 As such, any special shell "keywords" will not be interpreted.
因此,任何特殊的shell“关键字”都不会被解释。
If you try and exec cmd1 && cmd2
, what happens is that the arguments of the process are literally cmd1
, &&
, cmd2
. 如果您尝试执行
cmd1 && cmd2
,那么该过程的参数实际上是cmd1
, &&
, cmd2
。 Don't do that. 不要那样做。
What is more, don't use Runtime.exec()
. 更重要的是,不要使用
Runtime.exec()
。 Use a ProcessBuilder
instead. 请改用
ProcessBuilder
。 Sample code: 示例代码:
final Process p = new ProcessBuilder("cmd1", "arg1", "arg2").start();
final int retval = p.waitFor();
See the javadoc for ProcessBuilder
, it has a lot of niceties. 查看
ProcessBuilder
的javadoc,它有很多细节。
Oh, and if you use Java 7, don't even bother using external commands. 哦,如果你使用Java 7,甚至不用使用外部命令。 Java 7 has
Files.copy()
. Java 7有
Files.copy()
。
And also, man execve
. 而且,
man execve
也是如此。
The command and each of it's arguments must be separate items in a String array. 该命令及其每个参数必须是String数组中的单独项。 Eg:
例如:
private static final String[] COMMAND = { "cp", "-n", "/home/me/Downloads/a.png", "/home/me/Downloads/b.png" };
....
int result = Runtime.getRuntime().exec(COMMAND).waitFor();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.