tags:

views:

168

answers:

5

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

+5  A: 
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);
}
Zed
You want probably read the stream from getOutputStream or getErrorStream instead of the input.
JtR
It should be input stream. Just such naming convention.
Mykola Golubyev
Probably you should add p.waitFor() or something at the end?
Mykola Golubyev
A: 

I can do this in realtime?

What do you mean by "real time"?
romaintaz
Yes, you can do this while the program is running.
Charles Ma
This is not a forum! Please put additional aspects of your question into your original question.
DR
A: 

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
}
Rich Seller
A: 

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.

Brian Agnew
A: 

If you must use Runtime.exec(), you should read this.

duffymo