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?
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.
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!
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.
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.
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);
}
}
You could temporarily replace System.err or System.out with a stream that writes to string buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With