我想使用Runtime類來執行一些UNIX命令,但如果我嘗試使用cd
命令,則會出現問題。使用Java Runtime類運行多個unix命令
這裏是我的Java程序:
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
Process p = Runtime.getRuntime().exec("cd;cat test.txt|grep Hello");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception..");
e.printStackTrace();
System.exit(-1);
}
}
}
如果我執行這個然後我得到一個異常:
java.io.IOException: Cannot run program "cd": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at java.lang.Runtime.exec(Runtime.java:617)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at JavaRunCommand.main(JavaRunCommand.java:11)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
at java.lang.ProcessImpl.start(ProcessImpl.java:130)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
... 4 more
請讓我知道我們如何能夠運行多個命令,如果我想在Java中使用它。
'cd'是執行不是Binray。這是一個shell內置的命令。 –
'cd'是一個傳遞給可執行文件'/ bin/sh'的參數。 –
使用ProcessBuilder而不是Runtime.exec。 http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html –