1 7 8 package java.io; 9 10 34 public 35 class PushbackInputStream extends FilterInputStream { 36 40 protected byte[] buf; 41 42 50 protected int pos; 51 52 55 private void ensureOpen() throws IOException { 56 if (in == null) 57 throw new IOException ("Stream closed"); 58 } 59 60 74 public PushbackInputStream(InputStream in, int size) { 75 super(in); 76 if (size <= 0) { 77 throw new IllegalArgumentException ("size <= 0"); 78 } 79 this.buf = new byte[size]; 80 this.pos = size; 81 } 82 83 93 public PushbackInputStream(InputStream in) { 94 this(in, 1); 95 } 96 97 115 public int read() throws IOException { 116 ensureOpen(); 117 if (pos < buf.length) { 118 return buf[pos++] & 0xff; 119 } 120 return super.read(); 121 } 122 123 139 public int read(byte[] b, int off, int len) throws IOException { 140 ensureOpen(); 141 if ((off < 0) || (off > b.length) || (len < 0) || 142 ((off + len) > b.length) || ((off + len) < 0)) { 143 throw new IndexOutOfBoundsException (); 144 } 145 146 if (len == 0) { 147 return 0; 148 } 149 150 int avail = buf.length - pos; 151 if (avail > 0) { 152 if (len < avail) { 153 avail = len; 154 } 155 System.arraycopy(buf, pos, b, off, avail); 156 pos += avail; 157 off += avail; 158 len -= avail; 159 } 160 if (len > 0) { 161 len = super.read(b, off, len); 162 if (len == -1) { 163 return avail == 0 ? -1 : avail; 164 } 165 return avail + len; 166 } 167 return avail; 168 } 169 170 180 public void unread(int b) throws IOException { 181 ensureOpen(); 182 if (pos == 0) { 183 throw new IOException ("Push back buffer is full"); 184 } 185 buf[--pos] = (byte)b; 186 } 187 188 201 public void unread(byte[] b, int off, int len) throws IOException { 202 ensureOpen(); 203 if (len > pos) { 204 throw new IOException ("Push back buffer is full"); 205 } 206 pos -= len; 207 System.arraycopy(b, off, buf, pos, len); 208 } 209 210 221 public void unread(byte[] b) throws IOException { 222 unread(b, 0, b.length); 223 } 224 225 237 public int available() throws IOException { 238 ensureOpen(); 239 return (buf.length - pos) + super.available(); 240 } 241 242 261 public long skip(long n) throws IOException { 262 ensureOpen(); 263 if (n <= 0) { 264 return 0; 265 } 266 267 long pskip = buf.length - pos; 268 if (pskip > 0) { 269 if (n < pskip) { 270 pskip = n; 271 } 272 pos += pskip; 273 n -= pskip; 274 } 275 if (n > 0) { 276 pskip += super.skip(n); 277 } 278 return pskip; 279 } 280 281 290 public boolean markSupported() { 291 return false; 292 } 293 294 304 public synchronized void mark(int readlimit) { 305 } 306 307 319 public synchronized void reset() throws IOException { 320 throw new IOException ("mark/reset not supported"); 321 } 322 323 329 public synchronized void close() throws IOException { 330 if (in == null) 331 return; 332 in.close(); 333 in = null; 334 buf = null; 335 } 336 337 } 338 | Popular Tags |