1 18 package com.Ostermiller.util; 19 20 import java.io.*; 21 22 29 public class SizeLimitInputStream extends InputStream { 30 31 38 protected InputStream in; 39 40 48 protected long maxBytesToRead = 0; 49 50 58 protected long bytesRead = 0; 59 60 68 public long getBytesRead(){ 69 return bytesRead; 70 } 71 72 80 public long getBytesLeft(){ 81 return maxBytesToRead - bytesRead; 82 } 83 84 92 public boolean allBytesRead(){ 93 return getBytesLeft() == 0; 94 } 95 96 102 public long getMaxBytesToRead(){ 103 return maxBytesToRead; 104 } 105 106 115 public SizeLimitInputStream(InputStream in, long maxBytesToRead){ 116 this.in = in; 117 this.maxBytesToRead = maxBytesToRead; 118 } 119 120 123 public int read() throws IOException { 124 if (bytesRead >= maxBytesToRead){ 125 return -1; 126 } 127 int b = in.read(); 128 if(b != -1){ 129 bytesRead++; 130 } 131 return b; 132 } 133 134 137 public int read(byte[] b) throws IOException { 138 return this.read(b, 0, b.length); 139 } 140 141 144 public int read(byte[] b, int off, int len) throws IOException { 145 if (bytesRead >= maxBytesToRead){ 146 return -1; 147 } 148 long bytesLeft = getBytesLeft(); 149 if (len > bytesLeft){ 150 len = (int)bytesLeft; 151 } 152 int bytesJustRead = in.read(b, off, len); 153 bytesRead += bytesJustRead; 154 return bytesJustRead; 155 } 156 157 160 public long skip(long n) throws IOException { 161 if (bytesRead >= maxBytesToRead){ 162 return -1; 163 } 164 long bytesLeft = getBytesLeft(); 165 if (n > bytesLeft){ 166 n = bytesLeft; 167 } 168 return in.skip(n); 169 } 170 171 174 public int available() throws IOException { 175 int available = in.available(); 176 long bytesLeft = getBytesLeft(); 177 if (available > bytesLeft){ 178 available = (int)bytesLeft; 179 } 180 return available; 181 } 182 183 194 public void close() throws IOException { 195 in.close(); 196 } 197 198 201 public void mark(int readlimit) { 202 in.mark(readlimit); 203 } 204 205 208 public void reset() throws IOException { 209 in.reset(); 210 } 211 212 215 public boolean markSupported(){ 216 return in.markSupported(); 217 } 218 } 219 | Popular Tags |