View Javadoc

1   /*
2    *  Copyright 2006 Simon Raess
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.beep4j.internal.util;
17  
18  import java.io.IOException;
19  import java.io.Reader;
20  
21  /**
22   * Reader implementation that reads from a CharSequence. It's odd that
23   * this kind of reader does not exist in the standard Java library. It
24   * is similar to a StringReader but more generally applicable.
25   * 
26   * @author Simon Raess
27   */
28  public class CharSequenceReader extends Reader {
29  
30  	private final CharSequence sequence;
31  
32  	private int position;
33  	
34  	private boolean closed;
35  	
36  	public CharSequenceReader(CharSequence sequence) {
37  		Assert.notNull("sequence", sequence);
38  		this.sequence = sequence;
39  	}
40  	
41  	private int remaining() {
42  		return sequence.length() - position;
43  	}
44  	
45  	private void checkClosed() throws IOException {
46  		if (closed) {
47  			throw new IOException("stream is closed");
48  		}
49  	}
50  	
51  	@Override
52  	public int read() throws IOException {
53  		checkClosed();
54  		if (position >= sequence.length()) {
55  			return -1;
56  		} else {
57  			return sequence.charAt(position++);
58  		}
59  	}
60  	
61  	@Override
62  	public int read(char[] cbuf, int off, int len) throws IOException {
63  		checkClosed();
64  		int length = Math.min(len, remaining());
65  		for (int i = 0; i < length; i++) {
66  			cbuf[off + i] = sequence.charAt(position++);
67  		}
68  		return length > 0 ? length : -1;
69  	}
70  
71  	@Override
72  	public void close() throws IOException {
73  		closed = true;
74  	}
75  		
76  }