alberto
alberto

Reputation:

How can i get the console output generated by a exe file?

without using a redirect to file (">", ">>")

Upvotes: 3

Views: 10819

Answers (3)

Zed
Zed

Reputation: 57678

Process p = Runtime.getRuntime().exec("executable.exec");

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;
while ((line = input.readLine()) != null) {
  System.out.println(line);
}

Upvotes: 10

Rich Seller
Rich Seller

Reputation: 84088

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
}

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272417

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.

Upvotes: 0

Related Questions