|
0. Runtime.exec()用來執(zhí)行外部程序或命令
1. Runtime.exec() 有四種調(diào)用方法 * public Process exec(String command);
2. 得到程序執(zhí)行返回值, 0為success 需要用waitFor()函數(shù),比如 Process p = Runtime.getRuntime().exec("javac"); (處理.....)
3. 得到程序執(zhí)行的結(jié)果或錯(cuò)誤信息 需要用BufferedInputStream 和 BufferReader來得到,否則程序會(huì)hang 比如得到錯(cuò)誤信息用p.getErrorStream(),然后輸出即可: BufferedInputStream in = new BufferedInputStream(p.getErrorStream());
4. Runtime.exec() 不等同于直接執(zhí)行command line命令! 啊,我算是在這里吃了苦頭了。Runtime.exec()很有局限性,對(duì)有些命令不能直接把command line里的內(nèi)容當(dāng)作String參數(shù)傳給exec(). 比如重定向等命令。舉個(gè)例子: javap -l xxx > output.txt 這時(shí)要用到exec的第二種重載,即input 參數(shù)為String[]: Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","javap -l xxx > output.txt"});
轉(zhuǎn)載請(qǐng)注明本文出處:http://blog.csdn.net/flying881114/archive/2011/03/23/6272472.aspx
參考資料: 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 |
|
|