【发布时间】:2016-02-09 21:35:43
【问题描述】:
我正在尝试使用Runtime.getRuntime().exec(command) 从 Java 应用程序运行一些命令。但是,某些从命令行工具(如终端)运行的命令在这样执行时会失败。
例子:
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
}
请注意,COMMAND_2 与 COMMAND 有两次相同的作用,由 && 分隔。为什么一个成功,另一个失败?两者都可以在终端中正常工作。
我在 Red Hat Enterprise Linux 6 上使用 Oracle-Java 1.7.0。
【问题讨论】:
-
您可能需要为完全限定路径提供
cp,例如/bin/cp. -
尝试将 && 替换为 ';' 来执行
-
1.使用
ProcessBuilder; 2.Process不是shell解释器! -
@MiteshParmar 没有区别。 @fge 它到底是什么,即用于解释该命令的内容是什么?我发现它在以我的命令作为参数显式运行
bash时有效。 -
好吧,
bash是一个 shell 解释器的例子;而bash本身就是一个进程。但是没有理由对进程使用bash,除非你执行一个shell脚本。
标签: java linux shell command-line