1   /**
2    * LOGBack: the reliable, fast and flexible logging library for Java.
3    *
4    * Copyright (C) 1999-2006, QOS.ch
5    *
6    * This library is free software, you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation.
9    */
10  package ch.qos.logback.core.util;
11  
12  import java.io.ByteArrayOutputStream;
13  import java.io.IOException;
14  import java.io.OutputStream;
15  import java.io.PrintStream;
16  
17  /**
18   * This stream writes its output to the target PrintStream supplied to its
19   * constructor. At the same time, all the available bytes are collected and
20   * returned by the toString() method.
21   * 
22   * @author Ceki Gulcu
23   */
24  public class TeeOutputStream extends OutputStream {
25  
26    final PrintStream targetPS;
27    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
28  
29    public TeeOutputStream(PrintStream targetPS) {
30      // allow for null arguments
31      this.targetPS = targetPS;
32    }
33  
34    public void write(int b) throws IOException {
35      baos.write(b);
36      if(targetPS != null) {
37      targetPS.write(b);
38      }
39    }
40  
41    public String toString() {
42      return baos.toString();
43    }
44  
45    public byte[] toByteArray() {
46      return baos.toByteArray();
47    }
48  }