|
9 | 9 |
|
10 | 10 | /** All credit to Manasjyoti Sharma: https://stackoverflow.com/a/30665299 |
11 | 11 | */ |
12 | | -public class SystemOutCapturer { |
| 12 | +public abstract class SystemCapturer { |
| 13 | + |
13 | 14 | private ByteArrayOutputStream baos; |
14 | 15 | private PrintStream previous; |
15 | 16 | private boolean capturing; |
16 | 17 |
|
| 18 | + protected abstract PrintStream getOriginalStream(); |
| 19 | + |
| 20 | + protected abstract void setSystemStream( PrintStream stream ); |
| 21 | + |
17 | 22 | public void start() { |
18 | 23 | if (capturing) { |
19 | 24 | return; |
20 | 25 | } |
21 | 26 |
|
22 | 27 | capturing = true; |
23 | | - previous = System.out; |
| 28 | + previous = getOriginalStream(); |
24 | 29 | baos = new ByteArrayOutputStream(); |
25 | 30 |
|
26 | 31 | OutputStream outputStreamCombiner = |
27 | 32 | new OutputStreamCombiner(Arrays.asList(previous, baos)); |
28 | 33 | PrintStream custom = new PrintStream(outputStreamCombiner); |
29 | 34 |
|
30 | | - System.setOut(custom); |
| 35 | + setSystemStream(custom); |
31 | 36 | } |
32 | 37 |
|
33 | 38 | public String stop() { |
34 | 39 | if (!capturing) { |
35 | 40 | return ""; |
36 | 41 | } |
37 | 42 |
|
38 | | - System.setOut(previous); |
| 43 | + setSystemStream(previous); |
39 | 44 |
|
40 | 45 | String capturedValue = baos.toString(); |
41 | 46 |
|
@@ -71,4 +76,30 @@ public void close() throws IOException { |
71 | 76 | } |
72 | 77 | } |
73 | 78 | } |
| 79 | + |
| 80 | + public static class SystemOutCapturer extends SystemCapturer { |
| 81 | + |
| 82 | + @Override |
| 83 | + protected PrintStream getOriginalStream() { |
| 84 | + return System.out; |
| 85 | + } |
| 86 | + |
| 87 | + @Override |
| 88 | + protected void setSystemStream(PrintStream stream) { |
| 89 | + System.setOut(stream); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + public static class SystemErrCapturer extends SystemCapturer { |
| 94 | + |
| 95 | + @Override |
| 96 | + protected PrintStream getOriginalStream() { |
| 97 | + return System.err; |
| 98 | + } |
| 99 | + |
| 100 | + @Override |
| 101 | + protected void setSystemStream(PrintStream stream) { |
| 102 | + System.setErr(stream); |
| 103 | + } |
| 104 | + } |
74 | 105 | } |
0 commit comments