Đây là giải pháp thay cho ByteArrayOutputStream. Nó không thêm bất cứ điều gì vào ý tưởng của System.setOut. Thay vào đó, tôi muốn chia sẻ việc thực hiện tốt hơn là bắt mọi thứ vào ByteArrayOutputStream. Tôi chỉ muốn nắm bắt thông tin được chọn và cho phép tất cả các thông điệp tường trình xuất hiện trong bảng điều khiển khi chúng được ghi lại thay vì chụp tất cả mọi thứ vào một balckbox (kích thước nào?) Để xử lý sau.
/**
* 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
}
};
Dưới đây là một ví dụ của việc sử dụng các lớp:
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
@dfa, tôi không đồng ý. Nó thực sự tương tự nhưng đủ khác nhau. –
... được cấp câu trả lời giống nhau ... –
Chủ đề khác hiện có câu trả lời tốt hơn. Nó liên quan đến việc sử dụng quy tắc hệ thống jUnit StandardOutputStreamLog. Ngoài ra còn có các quy tắc hệ thống cho stderr và stdin. –