加倍System.out

时间:2012-10-29 12:24:15

标签: java outputstream printstream

我想将System.out条消息写入另一个OutputStream,但我仍然希望获得标准输出。

我找到了关于此类问题的答案Copy and Redirecting System.err Stream

  

简而言之,您需要做的是定义一个可以复制其输出的PrintStream,使用以下命令进行分配:

System.setErr(doubleLoggingPrintStream)

这是我到目前为止所做的:

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) {}
            }
        }
    }
}

这只是一个草案,但这是一个好方法吗?我是否有一种更好的解决方案无能为力,所以我正在寻找确认,想法和建议。

1 个答案:

答案 0 :(得分:3)

我认为有一个Apache库可以做到这一点(TeeOutputStream,感谢@Thilo)但是你的实现对我来说很好。