Created
August 5, 2021 12:33
-
-
Save daniele-athome/595e3998ddc9cbc75446584766456fed to your computer and use it in GitHub Desktop.
InputStream that reads up to a given size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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