【发布时间】:2016-04-06 09:30:41
【问题描述】:
在 Linux 和 Windows 上运行 exec 与在 Windows 上运行之间可能存在明显差异,所以我抓了一个演示,但在发送 cmdarray 的“hello world”时它也会崩溃。
“echo”命令的“命令数组”的正确用法是什么?
崩溃:
run:
echo hello world...? cannot open notepad
java.io.IOException: Cannot run program "echo hello world 1": error=2, No such file or directory
BUILD SUCCESSFUL (total time: 0 seconds)
改编代码:
package com.tutorialspoint;
public class RuntimeDemo {
public static void main(String[] args) {
try {
// create a new array of 2 strings
String[] cmdArray = new String[2];
// first argument is the program we want to open
cmdArray[0] = "echo hello world 1";
// second argument is a txt file we want to open with notepad
cmdArray[1] = "echo hello world 2";
// print a message
System.out.println("echo hello world...? cannot open notepad");
// create a process and execute cmdArray
Process process = Runtime.getRuntime().exec(cmdArray);
// print another message
System.out.println("example.txt should now open.");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
【问题讨论】:
-
另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用
exec并使用ProcessBuilder创建进程。
标签: java linux runtime exec runtime.exec