java将输出打印到多个textarea
时间: 2023-06-26 20:04:09 浏览: 100
你可以使用以下方法将Java的输出打印到多个textarea上:
1. 创建一个PrintStream对象来捕获System.out输出:
```
PrintStream printStream = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
// do nothing
}
});
```
2. 为每个textarea创建一个输出流并将其添加到PrintStream对象中:
```
OutputStream output1 = new OutputStream() {
@Override
public void write(int b) throws IOException {
textarea1.append(String.valueOf((char) b));
}
};
OutputStream output2 = new OutputStream() {
@Override
public void write(int b) throws IOException {
textarea2.append(String.valueOf((char) b));
}
};
printStream = new PrintStream(new MultiOutputStream(System.out, output1, output2));
```
3. 创建一个MultiOutputStream类,该类将输出流转发到多个输出流:
```
class MultiOutputStream extends OutputStream {
private final List<OutputStream> outputStreams;
MultiOutputStream(OutputStream... outputStreams) {
this.outputStreams = Arrays.asList(outputStreams);
}
@Override
public void write(int b) throws IOException {
for (OutputStream outputStream : outputStreams) {
outputStream.write(b);
}
}
@Override
public void flush() throws IOException {
for (OutputStream outputStream : outputStreams) {
outputStream.flush();
}
}
@Override
public void close() throws IOException {
for (OutputStream outputStream : outputStreams) {
outputStream.close();
}
}
}
```
4. 使用setOut方法将PrintStream对象设置为System.out:
```
System.setOut(printStream);
```
现在,当您调用System.out.println时,输出将被转发到多个textarea上。
阅读全文