Java執行.exe檔案

來源:互聯網
上載者:User

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 對象表示的進程已經終止

這裡只從錯誤流中讀取資訊, 如果編譯錯誤(可以從傳回值看出), 將錯誤資訊顯示出來...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.