How do I capture the stdout and stderr from an external program within a task?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Robert_Smith
Posted On:   Tuesday, July 30, 2002 02:53 AM

I would like to capture the stdout and stderr produced when running an external program so that I can parse this output. How can I do this?

Re: How do I capture the stdout and stderr from an external program within a task?

Posted By:   Erik_Hatcher  
Posted On:   Tuesday, July 30, 2002 11:06 AM

Also, there is an output property on to capture an external commands' output.

Re: How do I capture the stdout and stderr from an external program within a task?

Posted By:   Robert_Smith  
Posted On:   Tuesday, July 30, 2002 03:00 AM

This can be done by creating your own output streams and passing these as arguments to the constructor of the Execute class:


public class CaptureOutput extends Task {

private ExecuteStreamHandler executeStreamHandler;
private ByteArrayOutputStream stdoutBuffer;
private ByteArrayOutputStream stderrBuffer;

public CaptureOutput()
{
// Create an output stream to hold stdout
stdoutBuffer = new ByteArrayOutputStream();

// Create an output stream to hold stderr
stderrBuffer = new ByteArrayOutputStream();

// Create the ExecuteStreamHandler used by Ant's Execute class
executeStreamHandler = new PumpStreamHandler(
stdoutBuffer,
stderrBuffer);
}

public void execute() throws BuildException
{
// create the command line
Commandline cmd = new Commandline();
cmd.setExecutable("ls");

// use our custom output stream handler
Execute exe = new Execute(executeStreamHandler);
exe.setAntRun(project);
exe.setWorkingDirectory(project.getBaseDir());
exe.setCommandline(cmd.getCommandline());

try {
log("Running the CaptureOutput task...", Project.MSG_INFO);
int retCode = exe.execute();
} catch (IOException e){}
catch (BuildException e) {}

System.out.println("Here's the output:");
System.out.print(stdoutBuffer.toString());
}
}
About | Sitemap | Contact