다음은 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에 대한 시스템 규칙도 있습니다. –