Pregunta

I want to write System.out messages to another OutputStream, but I still want to have the standard output too.

I found an answer on this similar matter Copy and Redirecting System.err Stream:

In short what you need to do is define a PrintStream which can duplicate its output, assign this using:

System.setErr(doubleLoggingPrintStream)

This is what I made so far:

public class DoublerPrintStream extends PrintStream {

    private OutputStream forwarder;

    public DoublerPrintStream(OutputStream target, OutputStream forward) {
        super(target, true);
        this.forwarder = forward;
    }

    @Override
    public void write(byte[] b) throws IOException {
        try {
            synchronized (this) {
                super.write(b);
                forwarder.write(b);
                forwarder.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
        }
    }

    @Override
    public void write(byte[] buf, int off, int len) {
        try {
            synchronized (this) {
                super.write(buf, off, len);
                forwarder.write(buf, off, len);
                forwarder.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
        }
    }

    @Override
    public void write(int b) {
        try {
            synchronized (this) {
                super.write(b);
                forwarder.write(b);
                forwarder.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
        }
    }

    @Override
    public void flush() {
        super.flush();
        try { forwarder.flush(); } catch (IOException e) { }
    }

    @Override
    public void close() {
        super.close();
        if (forwarder != null) {
            try {
                forwarder.close();
            } catch (Exception e) {}
            }
        }
    }
}

This is just a draft, but is this a good approach? I'm kind of clueless whether there is a better solution, so I'm looking for confirmation, ideas and suggestions.

¿Fue útil?

Solución

I think there is an Apache library that does that (TeeOutputStream , thanks @Thilo) but your implementation looks good to me.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top