1 package org.xwt.mips.util;
5 public class SeekableInputStream implements SeekableData {
6 private byte[] buffer = new byte[4096];
7 private int bytesRead = 0;
8 private boolean eof = false;
10 private InputStream is;
12 public SeekableInputStream(InputStream is) { this.is = is; }
14 public int read(byte[] outbuf, int off, int len) throws IOException {
15 if(pos >= bytesRead && !eof) readTo(pos + 1);
16 len = Math.min(len,bytesRead-pos);
17 if(len <= 0) return -1;
18 System.arraycopy(buffer,pos,outbuf,off,len);
23 private void readTo(int target) throws IOException {
24 if(target >= buffer.length) {
25 byte[] buf2 = new byte[Math.max(buffer.length+Math.min(buffer.length,65536),target)];
26 System.arraycopy(buffer,0,buf2,0,bytesRead);
29 while(bytesRead < target) {
30 int n = is.read(buffer,bytesRead,buffer.length-bytesRead);
39 public int length() throws IOException {
40 while(!eof) readTo(bytesRead+4096);
44 public int write(byte[] buf, int off, int len) throws IOException { throw new IOException("read-only"); }
45 public void seek(int pos) { this.pos = pos; }
46 public int pos() { return pos; }
47 public void close() throws IOException { is.close(); }