Printing Runtime exec() OutputStream to console
-
30-09-2019 - |
Question
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();
}
}
}
Solution
You need to start a new thread that would read terminal output stream and copy it to the console, after you call process.waitFor()
OTHER TIPS
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 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();
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();
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.
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()));
I know this is a very old question, but a better alternate for the above answers would be
ProcessBuilder builder = new ProcessBuilder(command);
builder.inheritIO();
Process p = builder.start();
From the docs of ProcessBuilder.inheritIO()
,
Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.
Hope this helps someone!