Saturday, July 7, 2012

Executing a OS command in Java and capture the stdout

 Process proc = Runtime.getRuntime().exec("ls");
 InputStream is = proc.getInputStream();
 DataInputStream in = new DataInputStream(is);
 BufferedReader br = new BufferedReader(new InputStreamReader(in));
 String line = null;
 out.write("result<br/>");
 while ( (line = br.readLine()) != null) {
  out.write(line);
  out.write("<br/>");
 }
 
 out.write("end result<br/>");  


2 comments:

Raju Angani said...

You might want to check the method again, it doesn't work.

Pierluigi Vernetto said...

Raju, I did test it and it worked on Linux (of course "ls" is a Unix command)... the methodology, I admit, is a bit iffy, sometimes there is some synchronization issue. If you are working locally, the best thing is to redirect the Unix command stdout to a file, and then display the content of that file. Much safer.