package org.richin.io.Stream.util; 02 import java.io.BufferedInputStream; 03 import java.io.BufferedOutputStream; 04 import java.io.FileInputStream; 05 import java.io.FileOutputStream; 06 import java.io.IOException; 07 import java.io.InputStream; 08 import java.io.OutputStream; 09 /** 10 * 对流进行分流,同时将一个输入流写入多个输出流 11 * @author Administrator 12 * 13 */ 14 public class TeeOutputStream extends OutputStream { 15 private OutputStream out1; 16 private OutputStream out2; 17 public TeeOutputStream(OutputStream stream1, OutputStream stream2) 18 { 19 //调用父类的构造方法,传入需要过滤的流 20 //super(stream1); 21 out1 = stream1; 22 out2 = stream2; 23 } 24 //重写write方法 25 public void write(int b) throws IOException 26 { 27 out1.write(b); 28 out2.write(b); 29 } 30 //重写write方法 31 public void write(byte[] data, int offset, int length) throws IOException 32 { 33 out1.write(data, offset, length); 34 out2.write(data, offset, length); 35 } 36 //重写flush方法 37 public void flush() throws IOException 38 { 39 out1.flush(); 40 out2.flush(); 41 } 42 //重写close方法 43 public void close() throws IOException 44 { 45 out1.close(); 46 out2.close(); 47 } 48 public static void copy(InputStream in, OutputStream out) 49 throws IOException { 50 // 缓冲流 51 BufferedInputStream bin = new BufferedInputStream(in); 52 BufferedOutputStream bout = new BufferedOutputStream(out); 53 while (true) { 54 int datum = bin.read(); 55 if (datum == -1) 56 break; 57 bout.write(datum); 58 } 59 // 刷新缓冲区 60 bout.flush(); 61 } 62 //main方法 63 public static void main(String[] args) throws IOException { 64 FileInputStream fin = new FileInputStream("E:\gzml\gongzhens\yaxi\设计稿\快递.rar"); 65 FileOutputStream fout1 = new FileOutputStream("D:/快递.rar"); 66 FileOutputStream fout2 = new FileOutputStream("e:/快递.rar"); 67 TeeOutputStream tout = new TeeOutputStream(fout1, fout2); 68 TeeOutputStream.copy(fin, tout); 69 fin.close(); 70 tout.close(); 71 } 72 }