Re: Capturing stdout from runtime exec
On 2007-05-15, Lax <lax_reddy@hotmail.com> wrote:
Hello all,
I'm trying to run an Unix cmd from runtime exec and trying to capture
the cmd's output.
e.g., /usr/bin/echo Foo > Foo.txt
I'm expecting my Java program to echo Foo and redirect it to Foo.txt
file.
However, on running the program, I get " Foo > Foo.txt".
Looks like the greater than (>) operator is not being intepreted
properly.
Could anyone give me some pointers on this, please?
Interpreting ">" is done by a shell. See the comments added to your
example for a way to run tat command under a shell.
-------------------------------------------
import java.io.* ;
import java.lang.* ;
public class RunUnixCommand {
public static void main(String args[]) {
String s = null;
/* replace
String[] cmd = new String[4] ;
cmd[0] = "/usr/bin/echo" ;
cmd[1] = "Foo" ;
cmd[2] = ">" ;
cmd[3] = "Foo.txt" ;
System.out.println("Run CMD: " + cmd[0] + " " +
cmd[1] + " " + cmd[2] + " " + cmd[3] ) ;
with */
String [] cmd = {
"/bin/sh",
"-c",
"/usr/bin/echo Foo >Foo.txt"
};
System.out.print("Run CMD:");
for (int i = 0; i < cmd.length; i++) {
System.out.print(" " + cmd[i]);
}
System.out.println();
try {
Process p = Runtime.getRuntime().exec(cmd);
// The rest of the code will have problems if you exec other commands,
// such as one that writes more output than fits in the buffer between
// the exec'ed process and the Java program. You should not wait
// for the process to terminate before reading its output. You should
// read either the stdout or stderr in another thread.
int i = p.waitFor();
if (i == 0){
// STDOUT
BufferedReader input = new
BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = input.readLine()) != null)
{
System.out.println(s);
}
} else {
// STDERR
BufferedReader stderr = new
BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stderr.readLine()) !=
null) {
System.out.println(s);
}
}
} catch (Exception e) {
System.out.println(e) ;
}
}
}
Thanks for your time,
Lax