完整的答案撕裂并替换:
包装a
InputStream这样相对简单,以限制在发送数据结束之前将要传递的字节数。
FilterInputStream是针对这种一般性工作的,但是由于您必须重写此 特定 工作的几乎所有方法,因此它会妨碍您的工作。
这是解决方案的粗略做法:
import java.io.IOException;import java.io.InputStream;public class BoundedInputStream extends InputStream { private final InputStream data; private long bytesRemaining; public BoundedInputStream(InputStream data, long maxBytes) { this.data = data; bytesRemaining = Math.max(maxBytes, 0); } @Override public int available() throws IOException { return (int) Math.min(data.available(), bytesRemaining); } @Override public void close() throws IOException { data.close(); } @Override public synchronized void mark(int limit) { // does nothing } @Override public boolean markSupported() { return false; } @Override public int read(byte[] buf, int off, int len) throws IOException { if (bytesRemaining > 0) { int nRead = data.read( buf, off, (int) Math.min(len, bytesRemaining)); bytesRemaining -= nRead; return nRead; } else { return -1; } } @Override public int read(byte[] buf) throws IOException { return this.read(buf, 0, buf.length); } @Override public synchronized void reset() throws IOException { throw new IOException("reset() not supported"); } @Override public long skip(long n) throws IOException { long skipped = data.skip(Math.min(n, bytesRemaining)); bytesRemaining -= skipped; return skipped; } @Override public int read() throws IOException { if (bytesRemaining > 0) { int c = data.read(); if (c >= 0) { bytesRemaining -= 1; } return c; } else { return -1; } }}


