java程序中 外部有,java使用Runtime和Process类执行外部程序,runtimeprocess,要在java程序中执行外...

java使用Runtime和Process类执行外部程序,runtimeprocess,要在java程序中执行外

要在java程序中执行外部程序,需要使用Runtime类的exec()方法,该方法返回Process类的实例。

在下面的例子中我们执行Notepad.exe,写字板是没有输出的,但是在有些情况我们需要获得程序执行的输出结果。

Process类的getInputStream()方法可以用来读输出数据。

waitFor()方法保证在外部进程执行完毕之前java程序不会退出。

如下是实例代码:import java.io.DataInputStream;import java.io.IOException;/** * * @author byrx.net */public class Main { /** * This method executes an external program (Notepad.exe) * and waits for it to finish before exiting. */ public void executeExternalProgram() { try { //Get the reference to the Runtime instance Runtime runtime = Runtime.getRuntime(); //Run the external program and receive a reference to the process Process proc = runtime.exec("notepad.exe C:/test.txt"); //Read output data from the process while it has more DataInputStream bis = new DataInputStream(proc.getInputStream()); int _byte; while ((_byte = bis.read()) != -1) System.out.print((char)_byte); //Wait for the process to finish proc.waitFor(); } catch (IOException ex) { ex.printStackTrace(); } catch (InterruptedException ex) { ex.printStackTrace(); } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().executeExternalProgram(); }}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值