Home / Java Patterns and Pitfalls / Java Patterns and Pitfalls     frequal.com

HPO: A Library to Handle Process Output

Summary

When launching external processes from Java, their output must be handled to avoid the external processes from hanging. The HPO library lets you easily choose how the output should be handled:

Download

Follow this link to download HPO: hpo.jar

Usage

Sample Code -- Throw Away Output from a Process

Run ps but throw away the output.
import com.frequal.hpo.*;

...

    Process process = new ProcessBuilder("ps").start();
    HandleProcessOutput handler;

    handler = new HandleProcessOutput(process, "None");
    handler.waitForProcessToFinish();

Sample Code -- Look at Output After Process Finishes

Run ls -latr and record the output for later processing. In this case the output is printed on the console, but it
import com.frequal.hpo.*;

...

    Process process = new ProcessBuilder("ls", "-latr").start();
    HandleProcessOutput handler = new HandleProcessOutput(process, "String");
    handler.waitForProcessToFinish();

    System.out.println("Stdout string saved is: " + handler.getStdout());
    System.out.println("Stderr string saved is: " + handler.getStderr());

Command-line Usage

To try HPO from the command-line, run it like this:
Run 'ls -latr' and store results in strings
  java -jar hpo.jar String ls -latr

Run 'ps ax' and show the output on stdout
  java -jar hpo.jar Stdout ps ax

Run 'touch /dev/null' and discard the output
  java -jar hpo.jar None touch /dev/null

License

HPO is free for non-commercial use. For commercial inquiries, use the frequal.com forums.
Last modified on 9 Oct 2009 by AO

Copyright © 2024 Andrew Oliver