1 ////////////////////////////////////////////////////////////////////////////////
2 // MillScript-XML: an Open Spice interpreter and batch website creation tool
3 // Copyright (C) 2005 Kevin Rogers
4 //
5 // This file is part of MillScript-XML.
6 //
7 // MillScript-XML is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 2 of the License, or (at your option)
10 // any later version.
11 //
12 // MillScript-XML is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 // more details.
16 //
17 // You should have received a copy of the GNU General Public License along with
18 // MillScript-XML; if not, write to the Free Software Foundation, Inc., 59 Temple
19 // Place, Suite 330, Boston, MA 02111-1307 USA
20 ////////////////////////////////////////////////////////////////////////////////
21 package org.millscript.commons.xml.tokenizer;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.Reader;
26
27 /**
28 * A simple stream wrapper that reads bytes from a stream and presents them as
29 * characters, with no character set conversion and no buffering.
30 */
31 public class ByteAsCharReader extends Reader {
32
33 /**
34 * The underlying input stream.
35 */
36 private final InputStream inputStream;
37
38 /**
39 * Constructs a new byte as char reader, to read bytes/characters from the
40 * specified input stream.
41 *
42 * @param is the input stream to read bytes from
43 */
44 public ByteAsCharReader( final InputStream is ) {
45 this.inputStream = is;
46 }
47
48 /**
49 * @see java.io.Reader#close()
50 */
51 @Override
52 public void close() throws IOException {
53 this.inputStream.close();
54 }
55
56 /**
57 * @see java.io.Reader#read()
58 */
59 @Override
60 public int read() throws IOException {
61 return this.inputStream.read();
62 }
63
64 /**
65 * @see java.io.Reader#read(char[], int, int)
66 */
67 @Override
68 public int read( final char[] cbuf, final int off, final int len ) throws IOException {
69 for ( int i = off; i < ( len + off ); i++ ) {
70 final int ch = this.inputStream.read();
71 if ( ch == -1 ) {
72 if ( i == off ) {
73 // We've tried to read the first character, but we got EOF
74 return -1;
75 } else {
76 // We've read some characters, but we got EOF, so return
77 // the current offset
78 return i;
79 }
80 } else {
81 // Carry on reading
82 cbuf[ i ] = (char) ch;
83 }
84 }
85 return len;
86 }
87
88 /**
89 * @see java.io.Reader#ready()
90 */
91 @Override
92 public boolean ready() throws IOException {
93 return this.inputStream.available() != 0;
94 }
95
96 }