1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.util.io;
12
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.io.OutputStream;
16
17
18
19
20
21
22
23
24
25
26
27
28 public class TeeInputStream extends InputStream {
29 private byte[] skipBuffer;
30
31 private InputStream src;
32
33 private OutputStream dst;
34
35
36
37
38
39
40
41
42
43
44 public TeeInputStream(InputStream src, OutputStream dst) {
45 this.src = src;
46 this.dst = dst;
47 }
48
49
50 @Override
51 public int read() throws IOException {
52 byte[] b = skipBuffer();
53 int n = read(b, 0, 1);
54 return n == 1 ? b[0] & 0xff : -1;
55 }
56
57
58 @Override
59 public long skip(long count) throws IOException {
60 long skipped = 0;
61 long cnt = count;
62 final byte[] b = skipBuffer();
63 while (0 < cnt) {
64 final int n = src.read(b, 0, (int) Math.min(b.length, cnt));
65 if (n <= 0)
66 break;
67 dst.write(b, 0, n);
68 skipped += n;
69 cnt -= n;
70 }
71 return skipped;
72 }
73
74
75 @Override
76 public int read(byte[] b, int off, int len) throws IOException {
77 if (len == 0)
78 return 0;
79
80 int n = src.read(b, off, len);
81 if (0 < n)
82 dst.write(b, off, n);
83 return n;
84 }
85
86
87 @Override
88 public void close() throws IOException {
89 byte[] b = skipBuffer();
90 for (;;) {
91 int n = src.read(b);
92 if (n <= 0)
93 break;
94 dst.write(b, 0, n);
95 }
96 dst.close();
97 src.close();
98 }
99
100 private byte[] skipBuffer() {
101 if (skipBuffer == null)
102 skipBuffer = new byte[2048];
103 return skipBuffer;
104 }
105 }