Printing Runtime exec() OutputStream to co

2019-01-03 10:45发布

I am trying to get the OutputStream of the Process initiated by exec() to the console. How can this be done?

Here is some incomplete code:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;

public class RuntimeTests
{
    public static void main(String[] args)
    {
        File path = new File("C:\\Dir\\Dir2");
        String command = "cmd /c dir";
        Reader rdr = null;
        PrintStream prtStrm = System.out;
        try
        {
            Runtime terminal = Runtime.getRuntime();

            OutputStream rtm = terminal.exec(command, null, path).getOutputStream();
            prtStrm = new PrintStream(rtm);
            prtStrm.println();
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

6条回答
走好不送
2楼-- · 2019-01-03 10:54

I faced the similar problem and I am using the following code.

Process p = Runtime.getRuntime().exec(".....");
p.waitFor();

String line;

BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((line = error.readLine()) != null){
    System.out.println(line);
}
error.close();

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=input.readLine()) != null){
    System.out.println(line);
}

input.close();

OutputStream outputStream = p.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println();
printStream.flush();
printStream.close();
查看更多
放荡不羁爱自由
3楼-- · 2019-01-03 11:01

I believe this is what you're looking for:

  String line;
  Process p = Runtime.getRuntime().exec(...);
  BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
  while ((line = input.readLine()) != null) {
    System.out.println(line);
  }
  input.close();
查看更多
劫难
4楼-- · 2019-01-03 11:03

If you can use org.apache.commons.io.IOUTils from commons-io,

System.out.println(IOUtils.toString(process.getInputStream()));
System.err.println(IOUtils.toString(process.getErrorStream()));
查看更多
Anthone
5楼-- · 2019-01-03 11:05

Try VerboseProcess from jcabi-log:

String output = new VerboseProcess(new ProcessBuilder("foo.bat")).stdout();

The class starts a background thread, listens to the output stream, and logs it.

查看更多
一夜七次
6楼-- · 2019-01-03 11:06

I recently ran into this problem and just wanted to mention that since java 7 the process builder api has been expanded. This problem can now be solved with:

ProcessBuilder pb = new ProcessBuilder("yourcommand");
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process p = pb.start();

I hope this helps :)

查看更多
淡お忘
7楼-- · 2019-01-03 11:12

You need to start a new thread that would read terminal output stream and copy it to the console, after you call process.waitFor()

查看更多
登录 后发表回答