Skip to content

Instantly share code, notes, and snippets.

@daniele-athome
Created August 5, 2021 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniele-athome/595e3998ddc9cbc75446584766456fed to your computer and use it in GitHub Desktop.
Save daniele-athome/595e3998ddc9cbc75446584766456fed to your computer and use it in GitHub Desktop.
InputStream that reads up to a given size
import java.io.*;
public class LimitedInputStream extends InputStream {
private final InputStream stream;
private final long limit;
private long bytesRead;
public LimitedInputStream(InputStream stream, long limit) {
this.stream = stream;
this.limit = limit;
}
@Override
public int read() throws IOException {
checkBytesRead();
int data = stream.read();
if (data >= 0) {
bytesRead++;
checkBytesRead();
}
return data;
}
private void checkBytesRead() throws LimitExceededException {
if (bytesRead > limit) {
throw new LimitExceededException("Limit of " + limit + " bytes exceeded trying to read from stream");
}
}
public static class LimitExceededException extends IOException {
private static final long serialVersionUID = 5428528161336134045L;
private LimitExceededException(String message) {
super(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment