1 9 package javolution.io; 10 11 import j2me.lang.CharSequence; 12 import j2me.lang.IllegalStateException; 13 import java.io.IOException ; 14 import java.io.Reader ; 15 import javolution.lang.MathLib; 16 import javolution.lang.Reusable; 17 import javolution.text.Appendable; 18 import javolution.text.CharArray; 19 import javolution.text.Text; 20 import javolution.text.TextBuilder; 21 22 29 public final class CharSequenceReader extends Reader implements Reusable { 30 31 34 private CharSequence _input; 35 36 39 private int _index; 40 41 47 public CharSequenceReader() { 48 } 49 50 58 public CharSequenceReader setInput(CharSequence charSequence) { 59 if (_input != null) 60 throw new IllegalStateException ("Reader not closed or reset"); 61 _input = charSequence; 62 return this; 63 } 64 65 72 public boolean ready() throws IOException { 73 if (_input == null) 74 throw new IOException ("Reader closed"); 75 return true; 76 } 77 78 83 public void close() throws IOException { 84 if (_input != null) { 85 reset(); 86 } 87 } 88 89 98 public int read() throws IOException { 99 if (_input == null) 100 throw new IOException ("Reader closed"); 101 return (_index < _input.length()) ? _input.charAt(_index++) : -1; 102 } 103 104 115 public int read(char cbuf[], int off, int len) throws IOException { 116 if (_input == null) 117 throw new IOException ("Reader closed"); 118 final int inputLength = _input.length(); 119 if (_index >= inputLength) 120 return -1; 121 final int count = MathLib.min(inputLength - _index, len); 122 final Object csq = _input; 123 if (csq instanceof String ) { 124 String str = (String ) csq; 125 str.getChars(_index, _index + count, cbuf, off); 126 } else if (csq instanceof Text) { 127 Text txt = (Text) csq; 128 txt.getChars(_index, _index + count, cbuf, off); 129 } else if (csq instanceof TextBuilder) { 130 TextBuilder tb = (TextBuilder) csq; 131 tb.getChars(_index, _index + count, cbuf, off); 132 } else if (csq instanceof CharArray) { 133 CharArray ca = (CharArray) csq; 134 System 135 .arraycopy(ca.array(), _index + ca.offset(), cbuf, off, 136 count); 137 } else { for (int i = off, n = off + count, j = _index; i < n;) { 139 cbuf[i++] = _input.charAt(j++); 140 } 141 } 142 _index += count; 143 return count; 144 } 145 146 153 public void read(Appendable dest) throws IOException { 154 if (_input == null) 155 throw new IOException ("Reader closed"); 156 dest.append(_input); 157 } 158 159 public void reset() { 161 _index = 0; 162 _input = null; 163 } 164 165 } | Popular Tags |