Java执行.exe文件, 这里以Java调用g++编译程序为例讲解
(我的g++编译器的和程序都在H:/bin/gcc/bin这个目录)
先来看程序:
package wen.hui; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class TestExec { public static void main(String[] args) { TestExec javaExec = new TestExec(); javaExec.testProcess(); } public void testProcess() { try { String path = "H://bin//gcc//bin//"; String command = path + "g++ -o " + path + "test.exe " + path + "test.c"; Process process = Runtime.getRuntime().exec(command); /* * TestInputStream errorStream = new TestInputStream(process * .getErrorStream()); errorStream.start(); */ String line = null; //get the process's errorStream InputStream errorStream = process.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); System.out.println("-----------------error informaiton------"); while((line = reader.readLine()) != null) { System.out.println(line); } System.out.println("---------------error informaiton------/n"); int exitValue = process.waitFor(); System.out.println("Return Value:" + exitValue); reader.close(); errorStream.close(); process.destroy(); } catch (Exception e) { System.out.println("Exception...."); } } }
这里只是演示, 实际运用中, 不应该使用绝对路径....
现在来解释上面的程序,
其实很简单, 首先编写一个命令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 对象表示的进程已经终止 |
这里只从错误流中读取信息, 如果编译错误(可以从返回值看出), 将错误信息显示出来...
本文介绍如何使用Java程序调用g++编译器编译C++源代码,并展示了如何读取编译过程中的错误信息。
3875

被折叠的 条评论
为什么被折叠?



