Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Runtime exec() OutputStream to console

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();         }     } } 
like image 993
TheWolf Avatar asked Oct 14 '10 17:10

TheWolf


2 Answers

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(); 
like image 62
Benjamin Gruenbaum Avatar answered Oct 11 '22 10:10

Benjamin Gruenbaum


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(); 
like image 22
Stijn Geukens Avatar answered Oct 11 '22 09:10

Stijn Geukens