Capturing stdout from runtime exec
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?
-------------------------------------------
import java.io.* ;
import java.lang.* ;
public class RunUnixCommand {
public static void main(String args[]) {
String s = null;
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] ) ;
try {
Process p = Runtime.getRuntime().exec(cmd);
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