[轉]java調用外部程序Runtime.getRuntime().exec


Runtime.getRuntime().exec()方法主要用於執行外部的程序或命令

Runtime.getRuntime().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)

    在指定環境的獨立進程中執行指定的命令和變量

  • public Process exec(String command,String[] envp,File dir)

    在有指定環境和工作目錄的獨立進程中執行指定的字符串命令

  • public Process exec(String[] cmdarray,String[] envp,File dir)

    在指定環境和工作目錄的獨立進程中執行指定的命令和變量

我們先來比較exec(String command)與exec(String[] cmdArray)的區別,其實他們是等價的,最終都會調用:

exec(String[] cmdarray,String[] envp,File dir),我們看看方法exec(String cmdarray,String[] envp,File dir) throws IOException的實現代碼:

?
1
2
3
4
5
6
7
8
public  Process exec(String command, String[] envp, File dir)  throws  IOException {
     if  (command.length() ==  0 throw  new  IllegalArgumentException( "Empty command" );
     StringTokenizer st =  new  StringTokenizer(command);
     String[] cmdarray =  new  String[st.countTokens()];
     for  ( int  i =  0 ; st.hasMoreTokens(); i++)
         cmdarray[i] = st.nextToken();
     return  exec(cmdarray, envp, dir);
}

從上面的代碼,我們可以看出最終調用的代碼都是:exec(String[] cmdArray,String envp,File  dir)。exec(String command)相當於exec(command,null,null),exec(String[] cmdArray)相當於exec(cmdArray,null,null)。

參數說明

cmdarray - 包含所調用命令及其參數的數組。

envp - 字符串數組,其中每個元素的環境變量的設置格式為 name=value,如果子進程應該繼承當前進程的環境,或該參數為 null。

dir - 子進程的工作目錄;如果子進程應該繼承當前進程的工作目錄,則該參數為 null。

 

另外,執行exec(String command)不等同於直接執行command line命令,比如命令:

?
1
javap -l xxx > output.txt

這時要用exec(String[] cmdArray)。如例:

?
1
2
Process p = Runtime.getRuntime().exec( new  String[]{ "/bin/sh" , "-c" ,
     "javap -l xxx > output.txt" });

 

關於返回結果類型:Process,它有幾個方法:

1.destroy():殺掉子進程

2.exitValue():返回子進程的出口值,值 0 表示正常終止

3.getErrorStream():獲取子進程的錯誤流

4.getInputStream():獲取子進程的輸入流

5.getOutputStream():獲取子進程的輸出流

6.waitFor():導致當前線程等待,如有必要,一直要等到由該 Process 對象表示的進程已經終止。如果已終止該子進程,此方法立即返回。如果沒有終止該子進程,調用的線程將被阻塞,直到退出子進程,根據慣例,0 表示正常終止;

 (sun:所以,int exitValue = waitFor() 也可以用來檢測進程進程是否正常終止。)

 

(原文地址:http://km-moon11.iteye.com/blog/2258500)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM