Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Capturing System.err.println or Capturing a PrintStream

Tags:

java

io

stream

Java Newbie question :

I need to capture the text being written to a printStream by a 3rd party component.

The PrintStream is defaulted to System.err, but can be changed to another PrintStream.

Looking through the docs, I couldn't find an easy way to direct the contents of a PrintStream to a string writer / buffer.

Can someone please assist?

like image 738
Marty Pitt Avatar asked Feb 03 '09 15:02

Marty Pitt


People also ask

What is the difference between system out Println and system err Println?

println() will print to the standard out of the system you are using. On the other hand, System. err. println() will print to the standard error.

Why we use system err Println in Java?

err. println( is mostly used to output error texts. It gives output on the console with the default(black) color. It also gives output on the console but most of the IDEs give it a red color to differentiate.

Whats happening when you use System Out and System err?

err works like System. out except it is normally only used to output error texts. Some programs (like Eclipse) will show the output to System. err in red text, to make it more obvious that it is error text.

What is err in Java?

err. public static final PrintStream err. The "standard" error output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.


2 Answers

PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setOut(new PrintStream(pipeOut));
// now read from pipeIn
like image 108
Joao da Silva Avatar answered Sep 30 '22 09:09

Joao da Silva


import java.io.*;

public class Test {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("errors.txt");
        } catch(IOException ioe) {
            System.err.println("redirection not possible: "+ioe);
            System.exit(-1);
        }
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);
        System.err.println("goes into file");
    }
}
like image 39
Johannes Weiss Avatar answered Sep 30 '22 09:09

Johannes Weiss