输出流复制到它们的系统对应物

输出流复制到它们的系统对应物

本文介绍了如何将进程的输入/输出流复制到它们的系统对应物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题的跟进.答案是

将 Process out、err 和 input 流复制到系统版本

IOUtils.copy如下(修复各种编译错误后):

with IOUtils.copy as follows (after fixing various compilation errors):

import org.apache.commons.io.IOUtils;
import java.io.IOException;

public class Test {
    public static void main(String[] args)
            throws IOException, InterruptedException {
        final Process process = Runtime.getRuntime().exec("/bin/sh -i");
        new Thread(new Runnable() {public void run() {
            try {
                IOUtils.copy(process.getInputStream(), System.out);
            } catch (IOException e) {}
        } } ).start();
        new Thread(new Runnable() {public void run() {
            try {
                IOUtils.copy(process.getErrorStream(), System.err);
            } catch (IOException e) {}
        } } ).start();
        new Thread(new Runnable() {public void run() {
            try {
                IOUtils.copy(System.in, process.getOutputStream());
            } catch (IOException e) {}
        } } ).start();
        process.waitFor();
    }
}

然而,生成的代码不适用于诸如执行 sh -i 命令的交互式进程.在后一种情况下,对任何 sh 命令都没有响应.

However, the resulting code doesn't work for interactive processes like the one executing sh -i command. In the latter case there is no response to any of the sh commands.

所以我的问题是:您能否提出一种替代方法来复制适用于交互式流程的流?

So my question is: could you suggest an alternative to copy the streams that will work with interactive processes?

推荐答案

问题是 IOUtil.copy() 正在运行,而 InputStream 中有数据要复制.由于您的进程只是不时地产生数据,IOUtil.copy() 退出,因为它认为没有数据要复制.

The problem is that IOUtil.copy() is running while there is data in the InputStream to be copied. Since your process only produces data from time to time, IOUtil.copy() exits as it thinks there is no data to be copied.

只需手动复制数据并使用布尔值停止外面的线程形式:

Just copy data by hand and use a boolean to stop the thread form outside:

byte[] buf = new byte[1024];
int len;
while (threadRunning) {  // threadRunning is a boolean set outside of your thread
    if((len = input.read(buf)) > 0){
        output.write(buf, 0, len);
    }
}

这会读取与 inputStream 上可用字节一样多的块,并将它们全部复制到输出.InputStream 在内部放置线程 wait(),然后在数据可用时唤醒它.
因此,在这种情况下,它会尽可能高效.

This reads in chunks as many bytes as there are available on inputStream and copies all of them to output. Internally InputStream puts thread so wait() and then wakes it when data is available.
So it's as efficient as you can have it in this situation.

这篇关于如何将进程的输入/输出流复制到它们的系统对应物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 11:02