1 7 8 package java.io; 9 10 11 18 19 public class StringReader extends Reader { 20 21 private String str; 22 private int length; 23 private int next = 0; 24 private int mark = 0; 25 26 31 public StringReader(String s) { 32 this.str = s; 33 this.length = s.length(); 34 } 35 36 37 private void ensureOpen() throws IOException { 38 if (str == null) 39 throw new IOException ("Stream closed"); 40 } 41 42 50 public int read() throws IOException { 51 synchronized (lock) { 52 ensureOpen(); 53 if (next >= length) 54 return -1; 55 return str.charAt(next++); 56 } 57 } 58 59 71 public int read(char cbuf[], int off, int len) throws IOException { 72 synchronized (lock) { 73 ensureOpen(); 74 if ((off < 0) || (off > cbuf.length) || (len < 0) || 75 ((off + len) > cbuf.length) || ((off + len) < 0)) { 76 throw new IndexOutOfBoundsException (); 77 } else if (len == 0) { 78 return 0; 79 } 80 if (next >= length) 81 return -1; 82 int n = Math.min(length - next, len); 83 str.getChars(next, next + n, cbuf, off); 84 next += n; 85 return n; 86 } 87 } 88 89 105 public long skip(long ns) throws IOException { 106 synchronized (lock) { 107 ensureOpen(); 108 if (next >= length) 109 return 0; 110 long n = Math.min(length - next, ns); 112 n = Math.max(-next, n); 113 next += n; 114 return n; 115 } 116 } 117 118 125 public boolean ready() throws IOException { 126 synchronized (lock) { 127 ensureOpen(); 128 return true; 129 } 130 } 131 132 135 public boolean markSupported() { 136 return true; 137 } 138 139 152 public void mark(int readAheadLimit) throws IOException { 153 if (readAheadLimit < 0){ 154 throw new IllegalArgumentException ("Read-ahead limit < 0"); 155 } 156 synchronized (lock) { 157 ensureOpen(); 158 mark = next; 159 } 160 } 161 162 168 public void reset() throws IOException { 169 synchronized (lock) { 170 ensureOpen(); 171 next = mark; 172 } 173 } 174 175 178 public void close() { 179 str = null; 180 } 181 182 } 183 | Popular Tags |