1 30 31 package com.nightlabs.io; 32 33 import java.io.*; 34 35 44 public class LimitedInputStream extends InputStream 45 { 46 protected InputStream in; 47 protected int minLimit; 48 protected int maxLimit; 49 protected int readPos = 0; 50 51 52 56 public LimitedInputStream(InputStream in, int minLimit, int maxLimit) 57 { 58 this.in = in; 59 this.minLimit = minLimit; 60 this.maxLimit = maxLimit; 61 } 62 63 public int available() 64 throws IOException 65 { 66 int reallyAvailable = in.available(); 67 68 if (reallyAvailable < 0) { 69 if (readPos < minLimit) 70 throw new IOException("inputStream is closed; only "+readPos+" Bytes read, but minLimit = "+minLimit+" Bytes!"); 71 } 72 73 if (reallyAvailable <= 0) return reallyAvailable; 75 76 int limitedAvailable = Math.min( 77 reallyAvailable, 78 maxLimit - readPos 79 ); 80 81 86 if (limitedAvailable <= 0) 87 limitedAvailable = -1; 88 89 return limitedAvailable; 90 } 91 92 99 100 106 107 public boolean markSupported() 108 { 109 return false; 110 } 111 112 public int read() 113 throws java.io.IOException 114 { 115 if (readPos < maxLimit) { 116 int res = in.read(); 117 118 if (res >= 0) 119 readPos++; 120 else { 121 if (readPos < minLimit) 122 throw new IOException("inputStream is closed; only "+readPos+" Bytes read, but minLimit = "+minLimit+" Bytes!"); 123 } 124 125 return res; 126 } 127 else 128 return -1; 129 } 130 131 public int read(byte[] b) 132 throws IOException 133 { 134 return this.read(b, 0, b.length); 135 } 136 137 public int read(byte[] b, int off, int len) 138 throws IOException 139 { 140 if (readPos + len > maxLimit) 141 len = maxLimit - readPos; 142 143 if (len > 0) { 144 int bytesRead = in.read(b, off, len); 145 146 if (bytesRead > 0) 147 readPos += bytesRead; 148 149 if (bytesRead < 0 && readPos < minLimit) 150 throw new IOException("inputStream is closed; only "+readPos+" Bytes read, but minLimit = "+minLimit+" Bytes!"); 151 152 if (bytesRead == 0) 153 throw new IllegalStateException ("according to the documentation, InputStream.read(...) should never return 0 if len != 0, but it happened!"); 154 155 return bytesRead; 156 } 157 else if (len < 0) 158 throw new IndexOutOfBoundsException ("len < 0!"); 159 else 160 return -1; 161 } 162 163 169 170 public long skip(long len) 171 throws IOException 172 { 173 if (readPos + len > maxLimit) 174 len = maxLimit - readPos; 175 176 if (len > 0) { 177 long bytesSkipped = in.skip(len); 178 179 if (bytesSkipped > 0) 180 readPos += bytesSkipped; 181 182 return bytesSkipped; 183 } 184 else 185 return -1; 186 } 187 188 } | Popular Tags |