同时运行外部程序并通过stdin / stdout与之通信 [英] Run external program concurrently and communicate with it through stdin / stdout

查看:337
本文介绍了同时运行外部程序并通过stdin / stdout与之通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够与我的Java代码同时运行外部程序,即我想启动程序,然后将控制权返回给调用方法,同时保持外部程序同时运行。然后,Java代码将继续生成输入并将其发送到外部程序并接收输出。

I want to be able to run an external program concurrently with my Java code, i.e. I want to start the program, then return control to the calling method while keeping the external program running at the same time. The Java code will then keep generating input and send it to the external program and receive output back.

我不想继续加载外部程序,因为它有很高的开销。完成此任务的最佳方法是什么?谢谢!

I don't want to keep loading the external program as it has very high overhead. What is the best way to accomplish this? Thanks!

推荐答案

查看 ProcessBuilder 。设置 ProcessBuilder 并执行 start 后,您将拥有处理,您可以向其输入输入和读取输出。

Have a look at ProcessBuilder. Once you've set up the ProcessBuilder and executed start you'll have a handle to a Process to which you can feed input and read output.

这是一个可以帮助您入门的片段:

Here's a snippet to get you started:

ProcessBuilder pb = new ProcessBuilder("/bin/bash");
Process proc = pb.start();

// Start reading from the program
final Scanner in = new Scanner(proc.getInputStream());
new Thread() {
    public void run() {
        while (in.hasNextLine())
            System.out.println(in.nextLine());
    }
}.start();

// Write a few commands to the program.
PrintWriter out = new PrintWriter(proc.getOutputStream());
out.println("touch hello1");
out.flush();

out.println("touch hello2");
out.flush();

out.println("ls -la hel*");
out.flush();

out.close();

输出:

-rw-r--r-- 1 aioobe aioobe 0 2011-04-08 08:29 hello1
-rw-r--r-- 1 aioobe aioobe 0 2011-04-08 08:29 hello2

这篇关于同时运行外部程序并通过stdin / stdout与之通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆