Java执行.exe文件

本文介绍如何使用Java程序调用g++编译器编译C++源代码,并展示了如何读取编译过程中的错误信息。

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 对象表示的进程已经终止

这里只从错误流中读取信息, 如果编译错误(可以从返回值看出), 将错误信息显示出来...

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值