Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing contents of standard output in Java

I am invoking a function that is printing some string in my console/standard output. I need to capture this string. I cannot modify the function that is doing the printing, nor change runtime behavior through inheritance. I am unable to find any pre-defined methods that will allow me to do this.

Does the JVM store a buffer of printed contents?

Does anyone know of a Java method that will aid me?

like image 750
Shailesh Tainwala Avatar asked Mar 22 '11 10:03

Shailesh Tainwala


People also ask

What is the standard output of the Java program?

The standard output in Java is the PrintStream class accessed through the System. out field. By default, standard output prints to the display, also called the console. PrintStream allows the printing of different data types converting all data to bytes.

How do I save console output to string Java?

If you create a PrintStream connected to a ByteArrayOutputStream , then you can capture the output as a String . Example: // Create a stream to hold the output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); // IMPORTANT: Save the old System. out!

How do I save the output of a Java program?

Instantiate a PrintStream class by passing the above created File object as a parameter. Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.

What does System out Println mean?

Java System. out. println() is used to print an argument that is passed to it. The statement can be broken into 3 parts which can be understood separately as: System: It is a final class defined in the java.


2 Answers

You can redirect the standard output by calling

System.setOut(myPrintStream);

Or - if you need to log it at runtime, pipe the output to a file:

java MyApplication > log.txt

Another trick - if you want to redirect and can't change the code: Implement a quick wrapper that calls your application and start that one:

public class RedirectingStarter {
  public static void main(String[] args) {
    System.setOut(new PrintStream(new File("log.txt")));
    com.example.MyApplication.main(args);
  }
}
like image 104
Andreas Dolk Avatar answered Oct 15 '22 08:10

Andreas Dolk


You could temporarily replace System.err or System.out with a stream that writes to string buffer.

like image 28
Ingo Avatar answered Oct 15 '22 08:10

Ingo