Commons Io 简明教程
Apache Commons IO - TeeInputStream
它是一个 InputStream 代理,它透明地将从代理流中读取的所有字节的副本写入给定的 OutputStream。当调用此代理上的 close() 方法时,将关闭代理输入流。它可用于一次共同操作两个流。
It is an InputStream proxy that transparently writes a copy of all bytes which are read from the proxy stream to a given OutputStream. The proxy input stream is closed, when the close() method on this proxy is called. It can be used to operate two streams collectively at a time.
Class Declaration
以下是 org.apache.commons.io.input.TeeInputStream 类的声明 −
Following is the declaration for org.apache.commons.io.input.TeeInputStream Class −
public class TeeInputStream
extends ProxyInputStream
Example of TeeInputStream Class
在此示例中,关闭 TeeInputStream 会关闭 TeeInputStream 和 TeeOutputStream 对象。
In this example, closing a TeeInputStream closes the TeeInputStream as well as the TeeOutputStream objects.
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());
}
}
}
}