【问题标题】:Doubling System.out倍增系统.out
【发布时间】:2012-10-18 18:21:16
【问题描述】:

我想将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) {}
            }
        }
    }
}

这只是一个草稿,但这是一个好方法吗?我有点不知道是否有更好的解决方案,所以我正在寻找确认、想法和建议。

【问题讨论】:

标签: java outputstream printstream


【解决方案1】:

我认为有一个 Apache 库可以做到这一点(TeeOutputStream,感谢@Thilo),但您的实现对我来说看起来不错。

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 2020-04-25
    • 1970-01-01
    • 2019-03-26
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多