대표단 (모두 방법)을 실제 작업을 수행하는 포장 된 (원래) PrintStream
에 붙여 넣습니다. 메시지를 완전히 저장하는 방법은 필요에 따라 다릅니다 (마지막으로 작성된 String 만 저장하고 타임 스탬프의 맵을 저장하는 등). 당신이이 있으면, 당신은 (System.setOut()
를 통해) 자신의 구현 System.out
을 대체 할 수
public class RememberAllWrittenTextPrintStream extends PrintStream {
private static final String newLine = System.getProperty("line.separator");
private final StringBuffer sb = new StringBuffer();
private final PrintStream original;
public RememberAllWrittenTextPrintStream(PrintStream original) {
this.original = original;
}
public void print(double d) {
sb.append(d);
original.print(d);
}
public void print(String s) {
sb.append(s);
original.print(s);
}
public void println(String s) {
sb.append(s).append(newLine);
original.println(s);
}
public void println() {
sb.append(newLine);
original.println();
}
public void printf(String s, Object... args) {
sb.append(String.format(s, args));
original.printf(s, args);
}
// .....
// the same for ALL the public methods in PrintStream....
// (your IDE should help you easily create delegates for the `original` methods.)
public String getAllWrittenText() {
return sb.toString();
}
}
또한 스레드 안전을 돌볼 필요가 있습니다
(StringBuffer를이 스레드 안전하지만이보다 더 필요할 수 있습니다).
위가 있으면
수행 할 수 있습니다
RememberAllWrittenTextPrintStream ps
= new RememberAllWrittenTextPrintStream(System.out);
System.setOut(ps);
System.out.print("bla");
System.out.print("bla");
ps.getAllWrittenText(); // should now return "blabla"
편집 : 사용 println()
구현을 추가 플랫폼에 독립적 newLine
.
은 어디를 검색 할 수 있습니까? 인쇄 한 프로그램에서 불러 오시겠습니까? 아니면 다른 프로그램에서 읽고 싶습니까? – yankee
나는 일종의 일반 테스터를 만들기 위해 프로그램의 다른 부분에서 그것을 검색하고 싶었다. 이 답을 살펴 봄으로써, 테스터에게 환경을 보여줌으로써이 문제에 대한 더 나은 해결책을 찾았습니다. – SirLenz0rlot