这里是解决方案来代替ByteArrayOutputStream。它没有添加任何东西到System.setOut的想法。相反,我想分享比捕获ByteArrayOutputStream更好的实现。我更喜欢仅捕获选定的信息,并让所有日志消息在登录时出现在控制台中,而不是将所有内容都捕获到一个balckbox(具有哪种大小?)供以后处理。
/**
* Once started, std output is redirected to this thread.
* Thread redirects all data to the former system.out and
* captures some strings.*/
static abstract class OutputCaputre extends Thread {
// overrdie these methods for System.err
PrintStream getDownstream() { return System.out;}
void restoreDownstream() { System.setOut(downstream);}
// will be called for every line in the log
protected abstract void userFilter(String line);
final PrintStream downstream;
public final PipedInputStream pis;
private final PipedOutputStream pos;
OutputCaputre() throws IOException {
downstream = getDownstream();
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
System.setOut(new PrintStream(pos));
start();
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(pis));
// once output is resotred, we must terminate
while (true) {
String line = br.readLine();
if (line == null) {
return;
}
downstream.println(line);
userFilter(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void terminate() throws InterruptedException, IOException {
restoreDownstream(); // switch back to std
pos.close(); // there will be no more data - signal that
join(); // and wait until capture completes
}
};
以下是使用类的一个示例:
OutputCaputre outputCapture = new OutputCaputre() {
protected void userFilter(String line) {
downstream.println("Capture: " + line);
}
};
System.out.println("do you see me captured?");
// here is your test
outputCapture.terminate(); // finally, stop capturing
来源
2013-09-18 16:47:18
Val
@dfa,我不同意。它确实相似但不同。 –
...授予答案是一样的... –
另一个线程现在有一个更好的答案。它涉及使用jUnit StandardOutputStreamLog系统规则。还有stderr和stdin的系统规则。 –