TeeInputStream 类(TeeInputStream Class)

优质
小牛编辑
127浏览
2023-12-01

它是一个InputStream代理,它透明地将从代理流中读取的所有字节的副本写入给定的OutputStream。 调用此代理上的close()方法时,将关闭代理输入流。 它可以用于一次集体操作两个流。

Class 声明 (Class Declaration)

以下是org.apache.commons.io.input.TeeInputStream类的声明 -

public class TeeInputStream
   extends ProxyInputStream

TeeInputStream类的示例

在此示例中,关闭TeeInputStream会关闭TeeInputStream以及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 IoWiki. 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());
         }
      }
   }
}

输出 (Output)

它将打印以下结果。

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