java runtime 返回值_Java Runtime.exec()注意事项 | 学步园
轉載自:http://blog.csdn.net/flying881114/archive/2011/03/23/6272472.aspx
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/westwin/archive/2005/04/22/358377.aspx
http://blog.csdn.net/moreorless/archive/2009/05/15/4182883.aspx
http://blog.csdn.net/HEYUTAO007/archive/2010/06/30/5705499.aspx
總結
以上是生活随笔為你收集整理的java runtime 返回值_Java Runtime.exec()注意事项 | 学步园的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何看待315点名企业排队道歉!
- 下一篇: java io流学设置编码_Java学习