Run a command from a Java application dealing properly with stdin, stdout and stderr
If you want to run an external command from a Java application you have to deal properly with the input, output and error file descriptors or it won’t work. The key is to read the output and error buffers. This is a simple example on how to do this:
import java.io.*;
public class CmdExec {
public static void main(String argv[]) {
try {
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
// launch the command and grab stdin/stdout and stderr
Process process = Runtime.getRuntime().exec("ls -la");
stdin = process.getOutputStream();
stderr = process.getErrorStream();
stdout = process.getInputStream();
// You could write to sdtin too but it's useless for the ls we are doing ;)
line = "param1" + "n";
stdin.write(line.getBytes() );
stdin.flush();
line = "param2" + "n";
stdin.write(line.getBytes() );
stdin.flush();
stdin.close();
// clean up if any output in stdout
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
while ((line = brCleanUp.readLine()) != null) {
System.out.println ("[Stdout] " + line);
}
brCleanUp.close();
// clean up if any output in stderr
brCleanUp =
new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stderr] " + line);
}
brCleanUp.close();
System.out.println("Exit value: " + process.exitValue());
process.destroy();
} catch (Exception err) {
err.printStackTrace();
}
}
}