我想给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) {}
}
}
}
}
这只是一个草案,但这是一个好方法吗?我对是否有更好的解决方案一无所知,所以我正在寻找确认、想法和建议。