1 7 8 package java.io; 9 10 18 public 19 class CharArrayReader extends Reader { 20 21 protected char buf[]; 22 23 24 protected int pos; 25 26 27 protected int markedPos = 0; 28 29 33 protected int count; 34 35 39 public CharArrayReader(char buf[]) { 40 this.buf = buf; 41 this.pos = 0; 42 this.count = buf.length; 43 } 44 45 62 public CharArrayReader(char buf[], int offset, int length) { 63 if ((offset < 0) || (offset > buf.length) || (length < 0) || 64 ((offset + length) < 0)) { 65 throw new IllegalArgumentException (); 66 } 67 this.buf = buf; 68 this.pos = offset; 69 this.count = Math.min(offset + length, buf.length); 70 this.markedPos = offset; 71 } 72 73 74 private void ensureOpen() throws IOException { 75 if (buf == null) 76 throw new IOException ("Stream closed"); 77 } 78 79 84 public int read() throws IOException { 85 synchronized (lock) { 86 ensureOpen(); 87 if (pos >= count) 88 return -1; 89 else 90 return buf[pos++]; 91 } 92 } 93 94 104 public int read(char b[], int off, int len) throws IOException { 105 synchronized (lock) { 106 ensureOpen(); 107 if ((off < 0) || (off > b.length) || (len < 0) || 108 ((off + len) > b.length) || ((off + len) < 0)) { 109 throw new IndexOutOfBoundsException (); 110 } else if (len == 0) { 111 return 0; 112 } 113 114 if (pos >= count) { 115 return -1; 116 } 117 if (pos + len > count) { 118 len = count - pos; 119 } 120 if (len <= 0) { 121 return 0; 122 } 123 System.arraycopy(buf, pos, b, off, len); 124 pos += len; 125 return len; 126 } 127 } 128 129 141 public long skip(long n) throws IOException { 142 synchronized (lock) { 143 ensureOpen(); 144 if (pos + n > count) { 145 n = count - pos; 146 } 147 if (n < 0) { 148 return 0; 149 } 150 pos += n; 151 return n; 152 } 153 } 154 155 161 public boolean ready() throws IOException { 162 synchronized (lock) { 163 ensureOpen(); 164 return (count - pos) > 0; 165 } 166 } 167 168 171 public boolean markSupported() { 172 return true; 173 } 174 175 187 public void mark(int readAheadLimit) throws IOException { 188 synchronized (lock) { 189 ensureOpen(); 190 markedPos = pos; 191 } 192 } 193 194 200 public void reset() throws IOException { 201 synchronized (lock) { 202 ensureOpen(); 203 pos = markedPos; 204 } 205 } 206 207 210 public void close() { 211 buf = null; 212 } 213 } 214 | Popular Tags |