天天看點

java對IO流 進行分流

01    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   

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    }

繼續閱讀