Java執行.exe檔案, 這裡以Java調用g++編譯器為例講解
(我的g++編譯器的和程式都在H:/bin/gcc/bin這個目錄)
先來看程式:
package wen.hui;</p><p>import java.io.BufferedReader;<br />import java.io.InputStream;<br />import java.io.InputStreamReader;</p><p>public class TestExec {</p><p>public static void main(String[] args) {</p><p>TestExec javaExec = new TestExec();<br />javaExec.testProcess();<br />}</p><p>public void testProcess() {<br />try {</p><p>String path = "H://bin//gcc//bin//";<br />String command = path + "g++ -o " + path + "test.exe " + path + "test.c";<br />Process process = Runtime.getRuntime().exec(command);</p><p>/*<br /> * TestInputStream errorStream = new TestInputStream(process<br /> * .getErrorStream()); errorStream.start();<br /> */</p><p>String line = null;</p><p>//get the process's errorStream<br />InputStream errorStream = process.getErrorStream();<br />BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));</p><p>System.out.println("-----------------error informaiton------");<br />while((line = reader.readLine()) != null) {<br />System.out.println(line);<br />}<br />System.out.println("---------------error informaiton------/n");</p><p>int exitValue = process.waitFor();<br />System.out.println("Return Value:" + exitValue);<br />reader.close();<br />errorStream.close();<br />process.destroy();</p><p>} catch (Exception e) {<br />System.out.println("Exception....");<br />}<br />}</p><p>}<br />
這裡只是示範, 實際運用中, 不應該使用絕對路徑....
現在來解釋上面的程式,
其實很簡單, 首先編寫一個命令command, 如g++編譯.c程式的命令為: g++ -o test.exe test.c
Runtime.getRuntime()得到當前運行是環境,
然後調用它的exec(cmd)方法, 該方法返回一個進程process
查看process的API可以看到, process只有幾個方法, 卻很有用, 如下:
abstract void |
destroy() 殺掉子進程。 |
abstract int |
exitValue() 返回子進程的出口值。 |
abstract InputStream |
getErrorStream() 獲得子進程的錯誤流。 |
abstract InputStream |
getInputStream() 獲得子進程的輸入資料流。 |
abstract OutputStream |
getOutputStream() 獲得子進程的輸出資料流。 |
abstract int |
waitFor() 導致當前線程等待,如果必要,一直要等到由該 Process 對象表示的進程已經終止 |
這裡只從錯誤流中讀取資訊, 如果編譯錯誤(可以從傳回值看出), 將錯誤資訊顯示出來...