1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.beep4j.internal.util;
17
18 import java.io.IOException;
19 import java.io.Reader;
20
21
22
23
24
25
26
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 }