gpt4 book ai didi

java - 加倍 System.out

转载 作者:行者123 更新时间:2023-12-02 00:09:34 29 4
gpt4 key购买 nike

我想将 System.out 消息写入另一个 OutputStream,但我仍然想要标准输出。

我找到了类似问题的答案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)

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

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

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

最佳答案

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

关于java - 加倍 System.out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13121582/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com