java调用外部exe程序并传参

本文介绍如何使用Java调用外部程序,并展示了如何通过Runtime类获取运行时环境,使用exec方法启动外部进程,以及如何读取外部进程的输入、错误流等关键操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其实很简单, 首先编写一个命令command, 如g++编译.c程序的命令为: g++ -o test.exe test.c

Runtime.getRuntime()得到当前运行是环境,

然后调用它的exec(cmd)方法, 该方法返回一个进程process

查看process的API可以看到, process只有几个方法, 却很有用, 如下:

abstract  voiddestroy() 
          杀掉子进程。
abstract  intexitValue() 
          返回子进程的出口值。
abstract  InputStreamgetErrorStream() 
          获得子进程的错误流。
abstract  InputStreamgetInputStream() 
          获得子进程的输入流。
abstract  OutputStreamgetOutputStream() 
          获得子进程的输出流。
abstract  intwaitFor() 
          导致当前线程等待,如果必要,一直要等到由该 Process 对象表示的进程已经终止


传参的话就在调用exec方法时传入一个String[]数组,前面是cmd命令,后面是传入的参数

形如:

public class TestExe {
    public static void main(String[] args) {
        String[] cmd = {"Notepad.exe","d:/test.txt"};
        Process process = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            process = runtime.exec(cmd);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (process != null){
                process.destroy();
            }
        }
    }
}

http://blog.youkuaiyun.com/sinat_19171485/article/details/50052205



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值