TeeOutputStream.java

  1. /*
  2.  * Copyright (C) 2020, Michael Dardis. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.util.io;

  11. import java.io.IOException;
  12. import java.io.OutputStream;

  13. /**
  14.  * An output stream that writes all data to two streams.
  15.  *
  16.  * @since 5.7
  17.  */
  18. public class TeeOutputStream extends OutputStream {

  19.     private final OutputStream stream1;
  20.     private final OutputStream stream2;

  21.     /**
  22.      * Initialize a tee output stream.
  23.      *
  24.      * @param stream1 first output stream
  25.      * @param stream2 second output stream
  26.      */
  27.     public TeeOutputStream(OutputStream stream1, OutputStream stream2) {
  28.         this.stream1 = stream1;
  29.         this.stream2 = stream2;
  30.     }

  31.     /** {@inheritDoc} */
  32.     @Override
  33.     public void write(byte[] buf) throws IOException {
  34.         this.stream1.write(buf);
  35.         this.stream2.write(buf);
  36.     }

  37.     /** {@inheritDoc} */
  38.     @Override
  39.     public void write(byte[] buf, int off, int len) throws IOException {
  40.         this.stream1.write(buf, off, len);
  41.         this.stream2.write(buf, off, len);
  42.     }

  43.     /** {@inheritDoc} */
  44.     @Override
  45.     public void write(int b) throws IOException {
  46.         this.stream1.write(b);
  47.         this.stream2.write(b);
  48.     }

  49.     /** {@inheritDoc} */
  50.     @Override
  51.     public void flush() throws IOException {
  52.         this.stream1.flush();
  53.         this.stream2.flush();
  54.     }

  55.     /** {@inheritDoc} */
  56.     @Override
  57.     public void close() throws IOException {
  58.         try {
  59.             this.stream1.close();
  60.         } finally {
  61.             this.stream2.close();
  62.         }
  63.     }
  64. }