1
2
3
4
5
6
7
8
9
10
11
12 package ca.spaz.util;
13
14 import java.io.*;
15
16 /***
17 * This class implements an InputStream that counts the bytes that it has
18 * read.
19 *
20 * @author Chris Rose
21 */
22 public class CountableInputStream extends FilterInputStream {
23
24 private static final int DEAFULT_BUFFER_SIZE = 8192;
25
26 private long bytesRetrieved = 0;
27
28 private long markpos = -1;
29
30 /***
31 * Create a new <code>CountableInputStream</code> and wrap it around the
32 * supplied <code>InputStream</code>.
33 *
34 * @param in an <code>InputStream</code> object to count.
35 */
36 public CountableInputStream(InputStream in) {
37 super(in);
38 }
39
40
41
42
43 public synchronized int read() throws IOException {
44 int next = super.read();
45 if (next != -1) {
46 bytesRetrieved++;
47 }
48 return next;
49 }
50
51
52
53
54 public synchronized int read(byte[] b, int off, int len) throws IOException {
55 int next = super.read(b, off, len);
56 if (next != -1) {
57 bytesRetrieved += next;
58 }
59 return next;
60 }
61
62
63
64
65 public synchronized void mark(int readlimit) {
66 super.mark(readlimit);
67 markpos = bytesRetrieved;
68 }
69
70
71
72
73 public long skip(long n) throws IOException {
74 long next = super.skip(n);
75 bytesRetrieved += next;
76 return next;
77 }
78
79
80
81
82 public synchronized void reset() throws IOException {
83 bytesRetrieved = markpos;
84 super.reset();
85 }
86
87
88
89
90 public int read(byte[] b) throws IOException {
91 int next = super.read(b);
92 if (next != -1) {
93 bytesRetrieved += next;
94 }
95 return next;
96 }
97
98 /***
99 * Get a count of the bytes read by this stream.
100 * @return the number of bytes read by this stream.
101 */
102 public long getBytesRead() {
103 return bytesRetrieved;
104 }
105
106 }