set OutputStream for a process

半城伤御伤魂 提交于 2019-12-11 09:55:50

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6185024/set-outputstream-for-a-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!