without using a redirect to file (">", ">>")
Process p = Runtime.getRuntime().exec("executable.exec");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((String line = input.readLine()) != null) {
System.out.println(line);
}
If you use the Commandline type from plexus-utils, you can avoid a lot of the heavy lifting associated with commandline interaction, for example waiting for the process, escaping arguments etc. You can set the command to timeout if needed as well.
You can pass StreamConsumers to capture the stdout and stderr, the Commandline handling will pass the output to the consumers one line at a time.
Commandline cl = new Commandline();
cl.setExecutable( "dir" );
cl.setWorkingDirectory( workingDirectory.getAbsolutePath() );
cl.createArg().setValue( "/S" );
StreamConsumer consumer = new StreamConsumer() {
public void consumeLine( String line ) {
//do something with the line
}
};
StreamConsumer stderr = new StreamConsumer() {
public void consumeLine( String line ) {
//do something with the line
}
};
int exitCode;
try {
exitCode = CommandLineUtils.execute( cl, consumer, stderr, getLogger() );
} catch ( CommandLineException ex ) {
//handle exception
}
Note that you should consume stdout and stderr concurrently, to prevent blocking. See this answer for more details.
Note that you may be able to get away with just taking stdout and not stderr. However if you .exe generates an error in some scenario, then your parent process can then block on the extra (unexpected) stream data. So it's always best to run your stream gathering concurrently.