0. Runtime.exec()用來執行外部程式或命令
1. Runtime.exec() 有四種調用方法
* public Process exec(String command);
* public Process exec(String [] cmdArray);
* public Process exec(String command, String [] envp);
* public Process exec(String [] cmdArray, String [] envp);
2. 得到程式執行傳回值, 0為success
需要用waitFor()函數,比如
Process p = Runtime.getRuntime().exec("javac");
(處理.....)
int exitVal = p.waitFor();
3. 得到程式執行的結果或錯誤資訊
需要用BufferedInputStream 和 BufferReader來得到,否則程式會hang
比如得到錯誤資訊用p.getErrorStream(),然後輸出即可:
BufferedInputStream in = new BufferedInputStream(p.getErrorStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
4. Runtime.exec() 不等同於直接執行command line命令!
啊,我算是在這裡吃了苦頭了。Runtime.exec()很有局限性,對有些命令不能直接把command line裡的內容當作String參數傳給exec().
比如重新導向等命令。舉個例子:
javap -l xxx > output.txt
這時要用到exec的第二種重載,即input 參數為String[]:
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","javap -l xxx > output.txt"});
轉載請註明本文出處:http://blog.csdn.net/flying881114/archive/2011/03/23/6272472.aspx