01: package com.jclark.xml.sax;
02:
03: import java.io.Reader;
04: import java.io.InputStream;
05: import java.io.IOException;
06:
07: /**
08: * An InputStream of the UTF-16 encoding of a Reader.
09: *
10: * @version $Revision: 1.3 $ $Date: 1998/05/04 07:46:28 $
11: */
12: public class ReaderInputStream extends InputStream {
13: private Reader reader;
14: private static final int BUF_SIZE = 4096;
15: private char[] buf = new char[BUF_SIZE];
16: private int bufIndex = 0;
17: private int bufEnd = 1;
18: /* true if we have read the first nibble of the character at bufIndex
19: but not yet read the second */
20: private boolean nibbled = false;
21:
22: public ReaderInputStream(Reader reader) {
23: this .reader = reader;
24: buf[0] = '\ufeff';
25: }
26:
27: public synchronized int read() throws IOException {
28: if (nibbled) {
29: nibbled = false;
30: return buf[bufIndex++] & 0xff;
31: }
32: while (bufIndex == bufEnd) {
33: bufIndex = 0;
34: bufEnd = reader.read(buf, 0, buf.length);
35: if (bufEnd < 0) {
36: bufEnd = 0;
37: return -1;
38: }
39: }
40: nibbled = true;
41: return buf[bufIndex] >> 8;
42: }
43:
44: public synchronized int read(byte b[], int off, int len)
45: throws IOException {
46: if (len <= 0)
47: return 0;
48: int startOff = off;
49: if (nibbled) {
50: nibbled = false;
51: if (b != null)
52: b[off] = (byte) (buf[bufIndex] & 0xff);
53: bufIndex++;
54: off++;
55: len--;
56: }
57: while (len > 0) {
58: if (bufIndex == bufEnd) {
59: bufIndex = 0;
60: bufEnd = reader.read(buf, 0, buf.length);
61: if (bufEnd < 0) {
62: bufEnd = 0;
63: if (off != startOff)
64: break;
65: return -1;
66: }
67: if (bufEnd == 0)
68: return off - startOff;
69: }
70: if (len == 1) {
71: if (b != null)
72: b[off] = (byte) (buf[bufIndex] >> 8);
73: off++;
74: nibbled = true;
75: break;
76: }
77: if (b != null) {
78: b[off++] = (byte) (buf[bufIndex] >> 8);
79: b[off++] = (byte) (buf[bufIndex] & 0xff);
80: } else
81: off += 2;
82: len -= 2;
83: bufIndex++;
84: }
85: return off - startOff;
86: }
87:
88: public synchronized void close() throws IOException {
89: reader.close();
90: }
91: }
|