SystemOutHandler.java
2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package me.drton.jmavsim;
//import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class SystemOutHandler {
private PrintStream osPrintStream;
private SystemOutHandlerOutputStream os;
private boolean active;
private boolean logToStdOut;
public SystemOutHandler(boolean logToStdOut) {
this.active = false;
this.logToStdOut = logToStdOut;
this.osPrintStream = System.out;
this.os = new SystemOutHandlerOutputStream(new ArrayList<OutputStream>(1));
}
public void setLogToStdOut(boolean logToStdOut) {
this.logToStdOut = logToStdOut;
}
public void addOutputStream(OutputStream os) {
this.os.addStream(os);
}
public void removeOutputStream(OutputStream os) {
this.os.removeStream(os);
}
public void start(boolean clearStreams) {
if (this.active) {
return;
}
this.active = true;
if (clearStreams) {
os.clearStreams();
}
if (this.logToStdOut) {
os.addStream(this.osPrintStream);
}
System.setOut(new PrintStream(this.os));
}
public void stop() {
this.active = false;
System.setOut(osPrintStream);
}
private static class SystemOutHandlerOutputStream extends OutputStream {
private List<OutputStream> outputStreams;
public SystemOutHandlerOutputStream(List<OutputStream> outputStreams) {
this.outputStreams = outputStreams;
}
public void addStream(OutputStream os) {
if (!this.outputStreams.contains(os)) {
this.outputStreams.add(os);
}
}
public void removeStream(OutputStream os) {
if (this.outputStreams.contains(os)) {
this.outputStreams.remove(os);
}
}
public void clearStreams() {
this.outputStreams.clear();
}
public void write(int b) throws IOException {
for (OutputStream os : this.outputStreams) {
if (os != null) {
os.write(b);
}
}
}
public void flush() throws IOException {
for (OutputStream os : this.outputStreams) {
if (os != null) {
os.flush();
}
}
}
public void close() throws IOException {
for (OutputStream os : outputStreams) {
if (os != null) {
os.close();
}
}
}
}
}