Search code examples
javastdoutexecute

Catch stdout using java


What is the best way, how to catch stdout using java?

Demonstration:

PROGRAM A start PROGRAM B, PROGRAM B print some output to console (using System.println("...")), how can i catch from PROGRAM A output in console from PROGRAM B?

My way is:

start Program B and redirect the output to a file ( PROGRAM B > output.txt )

Is there any better way?

I hope, you understand me :-)

EDIT:

I found on internet code, its work:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String program = "config_dir\\lib\\TestProject.jar";
    // Run a java app in a separate system process
    Process proc;
    try {
        proc = Runtime.getRuntime().exec("java -jar " + program + " a b c");
        // Then retreive the process output
        InputStream in = proc.getInputStream();
        InputStream err = proc.getErrorStream();
        System.out.println(convertStreamToString(in));
    } catch (IOException ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    }


}                                        
private String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Solution

  • This is a minimum quantity of code to read the output of /bin/cat which copies a file to standard output:

        ProcessBuilder pb = new ProcessBuilder( "/bin/cat", "some.file" );
        Process process = pb.start();
        InputStream is = process.getInputStream();
        int c;
        while( (c = is.read()) != -1 ){
            System.out.print( (char)c + "-" );
        }
        process.waitFor();