1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.vfs.util;
18
19 import java.io.BufferedInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22
23 /***
24 * An InputStream that provides buffering and end-of-stream monitoring.
25 *
26 * @author <a href="mailto:adammurdoch@apache.org">Adam Murdoch</a>
27 * @version $Revision: 480428 $ $Date: 2006-11-29 07:15:24 +0100 (Mi, 29 Nov 2006) $
28 */
29 public class MonitorInputStream
30 extends BufferedInputStream
31 {
32 private boolean finished;
33 private long count;
34
35 public MonitorInputStream(final InputStream in)
36 {
37 super(in);
38 count = 0;
39 }
40
41 /***
42 * Reads a character.
43 */
44 public int read() throws IOException
45 {
46 if (finished)
47 {
48 return -1;
49 }
50
51 final int ch = super.read();
52 if (ch != -1)
53 {
54 count++;
55 return ch;
56 }
57
58
59 close();
60 return -1;
61 }
62
63 /***
64 * Reads bytes from this input stream.error occurs.
65 */
66 public int read(final byte[] buffer, final int offset, final int length)
67 throws IOException
68 {
69 if (finished)
70 {
71 return -1;
72 }
73
74 final int nread = super.read(buffer, offset, length);
75 if (nread != -1)
76 {
77 count += nread;
78 return nread;
79 }
80
81
82 close();
83 return -1;
84 }
85
86 /***
87 * Closes this input stream and releases any system resources
88 * associated with the stream.
89 */
90 public void close() throws IOException
91 {
92 if (finished)
93 {
94 return;
95 }
96
97
98 IOException exc = null;
99 try
100 {
101 super.close();
102 }
103 catch (final IOException ioe)
104 {
105 exc = ioe;
106 }
107
108
109 try
110 {
111 onClose();
112 }
113 catch (final IOException ioe)
114 {
115 exc = ioe;
116 }
117
118 finished = true;
119 if (exc != null)
120 {
121 throw exc;
122 }
123 }
124
125 /***
126 * Called after the stream has been closed. This implementation does
127 * nothing.
128 */
129 protected void onClose() throws IOException
130 {
131 }
132
133 /***
134 * Get the nuber of bytes read by this input stream
135 */
136 public long getCount()
137 {
138 return count;
139 }
140 }