1 /*
2 * Logback: the reliable, generic, fast and flexible logging framework.
3 * Copyright (C) 1999-2022, QOS.ch. All rights reserved.
4 *
5 * This program and the accompanying materials are dual-licensed under
6 * either the terms of the Eclipse Public License v1.0 as published by
7 * the Eclipse Foundation
8 *
9 * or (per the licensee's choosing)
10 *
11 * under the terms of the GNU Lesser General Public License version 2.1
12 * as published by the Free Software Foundation.
13 */
14 package ch.qos.logback.core.testUtil;
15
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStream;
19 import java.io.PrintStream;
20
21 /**
22 * This stream writes its output to the target PrintStream supplied to its
23 * constructor. At the same time, all the available bytes are collected and
24 * returned by the toString() method.
25 *
26 * @author Ceki Gulcu
27 */
28 public class TeeOutputStream extends OutputStream {
29
30 final PrintStream targetPS;
31 public final ByteArrayOutputStream baos = new ByteArrayOutputStream();
32
33 public TeeOutputStream(PrintStream targetPS) {
34 // allow for null arguments
35 this.targetPS = targetPS;
36 }
37
38 public void write(int b) throws IOException {
39 baos.write(b);
40 if (targetPS != null) {
41 targetPS.write(b);
42 }
43 }
44
45 public String toString() {
46 return baos.toString();
47 }
48
49 public byte[] toByteArray() {
50 return baos.toByteArray();
51 }
52 }