IO de Apache Commons - TeeInputStream

Es un proxy InputStream que escribe de forma transparente una copia de todos los bytes que se leen del flujo del proxy en un OutputStream determinado. El flujo de entrada del proxy se cierra cuando se llama al método close () en este proxy. Se puede utilizar para operar dos flujos de forma colectiva a la vez.

Declaración de clase

A continuación se muestra la declaración de org.apache.commons.io.input.TeeInputStream Clase -

public class TeeInputStream
   extends ProxyInputStream

Ejemplo de clase TeeInputStream

En este ejemplo, al cerrar un TeeInputStream, se cierran los objetos TeeInputStream y TeeOutputStream.

IOTester.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;
public class IOTester {
   private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy
   Learning.";
   public static void main(String[] args) {
      try {
         usingTeeInputStream();
      }catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }
   public static void usingTeeInputStream() throws IOException {
      TeeInputStream teeInputStream = null;
      TeeOutputStream teeOutputStream = null;
      try {
         ByteArrayInputStream inputStream = new
         ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
         ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
         ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
         teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
         teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);
         teeInputStream.read(new byte[SAMPLE.length()]);
         System.out.println("Output stream 1: " + outputStream1.toString());
         System.out.println("Output stream 2: " + outputStream2.toString());
      }catch (IOException e) {
         System.out.println(e.getMessage());
      } finally {
         //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
         try {
            teeInputStream.close();
         } catch (IOException e) {
            System.out.println(e.getMessage());
         }
      }
   }
}

Salida

Imprimirá el siguiente resultado.

Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.