0

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() : "";
}
PanTau
  • 73
  • 1
  • 7
  • 1
    It depends. Do you want standard output on a file or do you want to inspect it in program A? - Either way, look a java.lang.ProcessBuilder for options to handle standard output without requiring shell redirection. – laune Feb 15 '15 at 11:48
  • I want inspect it in program A. – PanTau Feb 15 '15 at 11:49
  • Tell us what is wrong with the outcome of your code. If you see an exception, post that exception. If the program writes something else then expected, write both expected and actual output. – kajacx Feb 15 '15 at 12:15
  • Also try `System.err.println(convertStreamToString(err));` sometimes error in starting program (`java` not in classpath, `.jar` file not found, etc) goes to the `stderr` of that newly creted process instead of causing exception in the original program. – kajacx Feb 15 '15 at 12:18
  • possible duplicate of [Capturing stdout when calling Runtime.exec](http://stackoverflow.com/questions/882772/capturing-stdout-when-calling-runtime-exec) – Joe Feb 15 '15 at 12:28

1 Answers1

0

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();
laune
  • 31,114
  • 3
  • 29
  • 42