1

我有一个字符串需要通过管道传输到外部程序,然后读回输出。我了解如何读回输出,但是如何将此字符串作为输入进行管道传输?谢谢!

4

2 回答 2

2

它是这样的(未编译和未经测试)

Process p = Runtime . getRuntime ( ) . exec ( ... ) ;
Writer w = new java . io . OutputStreamWriter ( p . getOutputStream ( ) ) ;
w . append ( yourString ) ;
w. flush ( ) ;
// read the input back
于 2010-08-05T02:19:49.483 回答
2

小心不要造成死锁。如果进程正在写入您未读取的数据,同时您正在写入未读取的数据,则在同一线程中读取/写入进程可能会出现问题。

我倾向于使用一点模式线来让 io 进入不同的线程:

import java.io.InputStream;
import java.io.OutputStream;

public final class Pipe implements Runnable {

    private final InputStream in;
    private final OutputStream out;

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

    public static void pipe(Process process) {
        pipe(process.getInputStream(), System.out);
        pipe(process.getErrorStream(), System.err);
        pipe(System.in, process.getOutputStream());
    }

    public static void pipe(InputStream in, OutputStream out) {
        final Thread thread = new Thread(new Pipe(in, out));
        thread.setDaemon(true);
        thread.start();
    }

    public void run() {
        try {
            int i = -1;

            byte[] buf = new byte[1024];

            while ((i = in.read(buf)) != -1) {
                out.write(buf, 0, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这可能适用于您想要做的事情,也可能不适用——也许您处理的是一组已建立的输入,这些输入保证在某些预期输出之后出现(反之亦然,或多次迭代)。即一些同步块和步骤类型的交互。

但是,如果您只是“观察”可能会出现的东西,那么这是朝着正确方向的良好开端。您将传入一些不同的流并在一些 java.util.concurrent 'await(long,TimeUnit)' 类型代码中工作以等待响应。Java IO 基本上永远在 read() 操作上阻塞,因此如果您没有从外部进程获得预期的响应,则将自己与这些线程分开将使您在一段时间后放弃。

于 2010-08-05T02:36:10.327 回答