我想将System.out消息写入另一个OutputStream,但我仍然希望有标准输出。
我在这个类似的问题上找到了答案,复制和重定向System.err流
简而言之,您需要做的是定义一个可以复制其输出的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) {}
}
}
}
}这只是一个草案,但这是一个好办法吗?我不知道是否有更好的解决方案,所以我正在寻找确认,想法和建议。
发布于 2012-10-29 12:29:39
我认为有一个Apache库可以做到这一点(TeeOutputStream,谢谢@Thilo),但在我看来,您的实现很好。
https://stackoverflow.com/questions/13121582
复制相似问题