为进程设置OutputStream [英] set OutputStream for a process

查看:157
本文介绍了为进程设置OutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题的简短代码:

Here is a snipped code of my problem:

Process process = Runtime.getRuntime().exec(command);
    if (process.waitFor() != 0)
        throw new Exception("error");
    reader = 
        new BufferedReader(new InputStreamReader(process.getInputStream()));

正在运行的过程正在产生巨大的输出.如果我将输出重定向到文件,则该过程将更快终止,然后在屏幕上打印输出(标准输出). 由于磁盘性能低下,文件系统许可等原因,我不希望将输出重定向到文件.

The running process is producing a huge output. If i redirect the output to a file, the process terminates quicker then printing the output on screen (standard output). I do not wish to redirect the output to a file, due to low performance of the disk, filesystem permission, etc..

执行process.waitFor()时,Java被阻塞,直到进程(被调用方)终止,这可能需要很长时间.因此,为了绕过此问题,我想将流程的标准输出重定向到读者的流输入(代码的最后一行).即,被调用方应向与阅读器链接的流产生输出,而不是在屏幕上打印输出.

When process.waitFor() is executed, Java is being blocked until the process (callee) is terminated, and that can take a long time. So in order to bypass this issue, I would like to redirect the process' standard output to reader's stream input (last line at the code). i.e., the callee should produce an output to a stream linked with the reader, instead to print the output on screen.

希望我很清楚.我不知道该怎么办?任何帮助都会很棒.

Hope I was clear enough. I wonder how may I do that? Any assistance will be great.

推荐答案

如果您不关心进程的输出,只需将其重定向到在Unix上为> /dev/null在Windows上为> NUL的空设备.所有输出将被丢弃,您不必担心文件权限,性能等.

If you don't care about the output of the process, just redirect to the null device which is > /dev/null on Unix or > NUL on Windows. All the output will be discarded and you won't have to worry about file permissions, performance etc.

如果您关心输出,请查看这篇文章,向您展示使用StreamGobbler读取进程的stdout/stderr的正确方法.

If you do care about the output, take a look at this post which shows you the right way of reading the stdout/stderr of a process using a StreamGobbler.

这篇关于为进程设置OutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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