1 package com.sun.org.apache.regexp.internal; 2 3 59 60 import java.io.InputStream ; 61 import java.io.IOException ; 62 63 67 public final class StreamCharacterIterator implements CharacterIterator 68 { 69 70 private final InputStream is; 71 72 73 private final StringBuffer buff; 74 75 76 private boolean closed; 77 78 79 public StreamCharacterIterator(InputStream is) 80 { 81 this.is = is; 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 116 public char charAt(int pos) 117 { 118 try 119 { 120 ensure(pos); 121 return buff.charAt(pos); 122 } 123 catch (IOException e) 124 { 125 throw new StringIndexOutOfBoundsException (e.getMessage()); 126 } 127 } 128 129 130 public boolean isEnd(int pos) 131 { 132 if (buff.length() > pos) 133 { 134 return false; 135 } 136 else 137 { 138 try 139 { 140 ensure(pos); 141 return (buff.length() <= pos); 142 } 143 catch (IOException e) 144 { 145 throw new StringIndexOutOfBoundsException (e.getMessage()); 146 } 147 } 148 } 149 150 151 private int read(int n) throws IOException 152 { 153 if (closed) 154 { 155 return 0; 156 } 157 158 int c; 159 int i = n; 160 while (--i >= 0) 161 { 162 c = is.read(); 163 if (c < 0) { 165 closed = true; 166 break; 167 } 168 buff.append((char) c); 169 } 170 return n - i; 171 } 172 173 174 private void readAll() throws IOException 175 { 176 while(! closed) 177 { 178 read(1000); 179 } 180 } 181 182 183 private void ensure(int idx) throws IOException 184 { 185 if (closed) 186 { 187 return; 188 } 189 190 if (idx < buff.length()) 191 { 192 return; 193 } 194 195 read(idx + 1 - buff.length()); 196 } 197 } 198 | Popular Tags |