在Java中运行子进程,正确地向其提供输入和输出

8
我使用Java中的Runtime exec()方法创建子进程。然而,由于子进程是一个交互式程序,我需要在它需要输入时及时提供输入。同时我也需要显示子进程的输出。最简单的方法是什么?
我之前使用StreamGobbler通过process.getInputStream()来显示程序输出。但是,我不知道如何确定程序何时等待输入以及何时使用proc.getOutputStream提供输入。我该怎么做?
2个回答

3

问问自己:“当我从命令行运行程序时,如何知道程序需要输入?”看看提示并根据提示输入数据。原则上是一样的,只不过你的代码需要解释程序的输出并提供正确的输入。

为了避免重复造轮子,看看ExpectJ和/或Expect4J,它们是Java实现的古老*nix Expect工具,旨在处理这种编程交互。


遇到了类似的问题,使用ExpectJ解决了它。这是一个非常直观的库,只用了我5分钟就让它工作了。好建议+1。 - codelidoo

3

您需要在子进程的流和 System 流(System.inSystem.outSystem.err)之间复制输入和输出。这与我最近的问题相关 (链接)。目前我找到的最佳解决方案是:

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.FileChannel;

class StreamCopier implements Runnable {
    private InputStream in;
    private OutputStream out;

    public StreamCopier(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    public void run() {
        try {
            int n;
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
                out.flush();
            }
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
}

class InputCopier implements Runnable {
    private FileChannel in;
    private OutputStream out;

    public InputCopier(FileChannel in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    public void run() {
        try {
            int n;
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer.array(), 0, n);
                out.flush();
            }
            out.close();
        }
        catch (AsynchronousCloseException e) {}
        catch (IOException e) {
            System.out.println(e);
        }
    }
}

public class Test {
    private static FileChannel getChannel(InputStream in)
            throws NoSuchFieldException, IllegalAccessException {
        Field f = FilterInputStream.class.getDeclaredField("in");
        f.setAccessible(true);
        while (in instanceof FilterInputStream)
            in = (InputStream)f.get((FilterInputStream)in);
        return ((FileInputStream)in).getChannel();
    }

    public static void main(String[] args)
            throws IOException, InterruptedException,
                   NoSuchFieldException, IllegalAccessException {
        Process process = Runtime.getRuntime().exec("sh -i +m");
        Thread outThread = new Thread(new StreamCopier(
                process.getInputStream(), System.out));
        outThread.start();
        Thread errThread = new Thread(new StreamCopier(
                process.getErrorStream(), System.err));
        errThread.start();
        Thread inThread = new Thread(new InputCopier(
                getChannel(System.in), process.getOutputStream()));
        inThread.start();
        process.waitFor();
        System.in.close();
        outThread.join();
        errThread.join();
        inThread.join();
    }
}

这里的难点在于从System.in中提取一个通道。如果没有这个通道,当子进程终止时,您将无法中断读取输入的线程。
这种方法有一个严重的缺点:关闭System.in后,您将无法再从中读取。我目前使用的解决方法是使用单个输入重定向线程用于所有子进程。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接