Limitar el tamaño de un OutputStream

public class LimitedSizeOutputStream extends OutputStream {

private final OutputStream delegate;
private final long limit;
private long written = 0L;

/**
* Creates a stream wrapper that will throw an IOException if the write
* limit is exceeded.
*
* @param delegate
* the underlying stream
* @param limit
* the maximum number of bytes this stream will accept
*/
public LimitedSizeOutputStream(OutputStream delegate, long limit) {
this.delegate = delegate;
this.limit = limit;
}

private void checkLimit(long byteCount) throws IOException {
if (byteCount + written > limit) {
throw new IOException("Exceeded stream size limit");
}
written += byteCount;
}

@Override
public void write(int b) throws IOException {
checkLimit(1);
delegate.write(b);
}

@Override
public void write(byte[] b) throws IOException {
checkLimit(b.length);
delegate.write(b);
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
checkLimit(len);
delegate.write(b, off, len);
}

@Override
public void close() throws IOException {
delegate.close();
}

}

Comentarios