1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.any23.util;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.Reader;
23
24
25
26
27
28 public class ReaderInputStream extends InputStream {
29
30
31 private Reader in;
32
33 private String encoding = System.getProperty("file.encoding");
34
35 private byte[] slack;
36
37 private int begin;
38
39
40
41
42
43
44
45 public ReaderInputStream(Reader reader) {
46 in = reader;
47 }
48
49
50
51
52
53
54
55
56
57 public ReaderInputStream(Reader reader, String encoding) {
58 this(reader);
59 if (encoding == null) {
60 throw new IllegalArgumentException("encoding must not be null");
61 } else {
62 this.encoding = encoding;
63 }
64 }
65
66
67
68
69
70
71
72
73
74 public synchronized int read() throws IOException {
75 if (in == null) {
76 throw new IOException("Stream Closed");
77 }
78
79 byte result;
80 if (slack != null && begin < slack.length) {
81 result = slack[begin];
82 if (++begin == slack.length) {
83 slack = null;
84 }
85 } else {
86 byte[] buf = new byte[1];
87 if (read(buf, 0, 1) <= 0) {
88 result = -1;
89 }
90 result = buf[0];
91 }
92
93 if (result < -1) {
94 result += 256;
95 }
96
97 return result;
98 }
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115 public synchronized int read(byte[] b, int off, int len) throws IOException {
116 if (in == null) {
117 throw new IOException("Stream Closed");
118 }
119
120 while (slack == null) {
121 char[] buf = new char[len];
122 int n = in.read(buf);
123 if (n == -1) {
124 return -1;
125 }
126 if (n > 0) {
127 slack = new String(buf, 0, n).getBytes(encoding);
128 begin = 0;
129 }
130 }
131
132 if (len > slack.length - begin) {
133 len = slack.length - begin;
134 }
135
136 System.arraycopy(slack, begin, b, off, len);
137
138 if ((begin += len) >= slack.length) {
139 slack = null;
140 }
141
142 return len;
143 }
144
145
146
147
148
149
150
151 public synchronized void mark(final int limit) {
152 try {
153 in.mark(limit);
154 } catch (IOException ioe) {
155 throw new RuntimeException(ioe.getMessage());
156 }
157 }
158
159
160
161
162
163
164
165 public synchronized int available() throws IOException {
166 if (in == null) {
167 throw new IOException("Stream Closed");
168 }
169 if (slack != null) {
170 return slack.length - begin;
171 }
172 if (in.ready()) {
173 return 1;
174 } else {
175 return 0;
176 }
177 }
178
179
180
181
182 public boolean markSupported() {
183 return false;
184 }
185
186
187
188
189
190
191
192 public synchronized void reset() throws IOException {
193 if (in == null) {
194 throw new IOException("Stream Closed");
195 }
196 slack = null;
197 in.reset();
198 }
199
200
201
202
203
204
205
206 public synchronized void close() throws IOException {
207 if (in != null) {
208 in.close();
209 slack = null;
210 in = null;
211 }
212 }
213 }