为进程设置OutputStream

发布于 2024-11-10 14:37:55 字数 541 浏览 4 评论 0原文

这是我的问题的代码片段:

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

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

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

希望我说得足够清楚。我想知道我该怎么做?任何帮助都会很棒。

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..

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏末染殇 2024-11-17 14:37:55

如果您不关心该过程的输出,只需重定向到空设备,即 > Unix 上的 /dev/null> Windows 上的 NUL。所有输出都将被丢弃,您不必担心文件权限、性能等。

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

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.

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.

花之痕靓丽 2024-11-17 14:37:55

您需要在调用 waitFor() 之前读取输出。目前,您正在等待它完成,只有当它完成生成输出时,它才能执行此操作,但它无法执行此操作,因为您没有读取输出,因此它的缓冲区已满并且处于阻塞状态。

You need to read the output before calling waitFor(). At the moment you are waiting for it to finish, which it can only do when it has finished producing output, which it can't do because you aren't reading the output, so its buffers are full and it is blocking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文