首先,您必须创建一个从OutputStream接口继承的类以实现适配器模式(我不确定是否是adapter)
那么您可以使用该类作为波纹管
主要
PrintStream finalStream;
TreeOutputStream tos;
PrintStream out;
out = new PrintStream("logs.txt");
tos = new TreeOutputStream();
tos.add(out);
tos.add(System.out);
finalStream = new PrintStream(tos);
System.setOut(finalStream);
TreeOutputStream
public class TreeOutputStream extends OutputStream{
private final List streams;
public void add(OutputStream os){
streams.add(os);
}
public void remove(OutputStream os){
streams.remove(os);
}
public TreeOutputStream() {
streams = new ArrayList<>();
}
@Override
public void write(int i) throws IOException {
streams.stream().forEach(strm->{
try {
strm.write(i);
} catch (IOException ex) {
Logger.getLogger(TreeOutputStream.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
}
发生什么情况,您的输出流将遍历所有调用其write方法的流