1 21 24 package org.lobobrowser.util.io; 25 26 import java.io.*; 27 28 36 public class RecordedInputStream extends InputStream { 37 private final InputStream delegate; 38 private final ByteArrayOutputStream store = new ByteArrayOutputStream(); 39 private boolean hasReachedEOF = false; 40 private int markPosition = -1; 41 private int readPosition = -1; 42 private byte[] resetBuffer = null; 43 44 47 public RecordedInputStream(InputStream delegate) { 48 super(); 49 this.delegate = delegate; 50 } 51 52 55 public int read() throws IOException { 56 if(this.readPosition != -1 && this.readPosition < this.resetBuffer.length) { 57 int b = this.resetBuffer[this.readPosition]; 58 this.readPosition++; 59 return b; 60 } 61 else { 62 int b = this.delegate.read(); 63 if(b != -1) { 64 this.store.write(b); 65 } 66 else { 67 this.hasReachedEOF = true; 68 } 69 return b; 70 } 71 } 72 73 74 77 public int available() throws IOException { 78 return this.delegate.available(); 79 } 80 81 84 public void close() throws IOException { 85 this.delegate.close(); 86 } 87 88 91 public boolean markSupported() { 92 return true; 93 } 94 95 public synchronized void mark(int readlimit) { 96 this.markPosition = this.store.size(); 97 } 98 99 public synchronized void reset() throws IOException { 100 int mp = this.markPosition; 101 byte[] wholeBuffer = this.store.toByteArray(); 102 byte[] resetBuffer = new byte[wholeBuffer.length - mp]; 103 System.arraycopy(wholeBuffer, mp, resetBuffer, 0, resetBuffer.length); 104 this.resetBuffer = resetBuffer; 105 this.readPosition = 0; 106 } 107 108 111 public int read(byte[] buffer, int offset, int length) throws IOException { 112 if(this.readPosition != -1 && this.readPosition < this.resetBuffer.length) { 113 int minLength = Math.min(this.resetBuffer.length - this.readPosition, length); 114 System.arraycopy(this.resetBuffer, this.readPosition, buffer, offset, minLength); 115 this.readPosition += minLength; 116 return minLength; 117 } 118 else { 119 int numRead = this.delegate.read(buffer, offset, length); 120 if(numRead != -1) { 121 this.store.write(buffer, offset, numRead); 122 } 123 else { 124 this.hasReachedEOF = true; 125 } 126 return numRead; 127 } 128 } 129 130 public byte[] getBytesRead() { 131 return this.store.toByteArray(); 132 } 133 134 public String getString(String encoding) throws java.io.UnsupportedEncodingException { 135 byte[] bytes = this.store.toByteArray(); 136 return new String (bytes, encoding); 137 } 138 139 public boolean hasReachedEOF() { 140 return this.hasReachedEOF; 141 } 142 } 143 | Popular Tags |