同时运行外部程序并通过stdin/stdout与它通信

j.l*_*lee 7 java

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

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

aio*_*obe 11

看看ProcessBuilder.设置ProcessBuilder并执行后,start您将拥有一个Process可以输入输入和读取输出的句柄.

这是一个让你入门的片段:

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();
Run Code Online (Sandbox Code Playgroud)

输出:

-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
Run Code Online (Sandbox Code Playgroud)