1 package org.apache.regexp; 2 3 59 60 import java.io.Reader ; 61 import java.io.IOException ; 62 63 67 public final class ReaderCharacterIterator implements CharacterIterator 68 { 69 70 private final Reader reader; 71 72 73 private final StringBuffer buff; 74 75 76 private boolean closed; 77 78 79 public ReaderCharacterIterator(Reader reader) 80 { 81 this.reader = reader; 82 this.buff = new StringBuffer (512); 83 this.closed = false; 84 } 85 86 87 public String substring(int offset, int length) 88 { 89 try 90 { 91 ensure(offset + length); 92 return buff.toString().substring(offset, length); 93 } 94 catch (IOException e) 95 { 96 throw new StringIndexOutOfBoundsException (e.getMessage()); 97 } 98 } 99 100 101 public String substring(int offset) 102 { 103 try 104 { 105 readAll(); 106 return buff.toString().substring(offset); 107 } 108 catch (IOException e) 109 { 110 throw new StringIndexOutOfBoundsException (e.getMessage()); 111 } 112 } 113 114 115 public char charAt(int pos) 116 { 117 try 118 { 119 ensure(pos); 120 return buff.charAt(pos); 121 } 122 catch (IOException e) 123 { 124 throw new StringIndexOutOfBoundsException (e.getMessage()); 125 } 126 } 127 128 129 public boolean isEnd(int pos) 130 { 131 if (buff.length() > pos) 132 { 133 return false; 134 } 135 else 136 { 137 try 138 { 139 ensure(pos); 140 return (buff.length() <= pos); 141 } 142 catch (IOException e) 143 { 144 throw new StringIndexOutOfBoundsException (e.getMessage()); 145 } 146 } 147 } 148 149 150 private int read(int n) throws IOException 151 { 152 if (closed) 153 { 154 return 0; 155 } 156 157 char[] c = new char[n]; 158 int count = 0; 159 int read = 0; 160 161 do 162 { 163 read = reader.read(c); 164 if (read < 0) { 166 closed = true; 167 break; 168 } 169 count += read; 170 buff.append(c, 0, read); 171 } 172 while (count < n); 173 174 return count; 175 } 176 177 178 private void readAll() throws IOException 179 { 180 while(! closed) 181 { 182 read(1000); 183 } 184 } 185 186 187 private void ensure(int idx) throws IOException 188 { 189 if (closed) 190 { 191 return; 192 } 193 194 if (idx < buff.length()) 195 { 196 return; 197 } 198 read(idx + 1 - buff.length()); 199 } 200 } 201 | Popular Tags |