diff src/goodjava/io/FixedLengthInputStream.java @ 1490:9a2a2181a58f

FixedLengthInputStream
author Franklin Schmidt <fschmidt@gmail.com>
date Sat, 02 May 2020 20:42:28 -0600
parents src/goodjava/io/LimitedInputStream.java@1f41e5921090
children 91c167099462
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/goodjava/io/FixedLengthInputStream.java	Sat May 02 20:42:28 2020 -0600
@@ -0,0 +1,68 @@
+package goodjava.io;
+
+import java.io.InputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.EOFException;
+
+
+public class FixedLengthInputStream extends FilterInputStream {
+	protected long left;
+
+	public FixedLengthInputStream(InputStream in, long len) {
+		super(in);
+		if( len < 0 )
+			throw new IllegalArgumentException("len can't be negative");
+		this.left = len;
+	}
+
+	public synchronized int read() throws IOException {
+		if( left == 0 )
+			return -1;
+		int n = super.read();
+		if( n == -1 )
+			throw new EOFException();
+		left--;
+		return n;
+	}
+
+	public synchronized int read(byte[] b, int off, int len) throws IOException {
+		if( len == 0 )
+			return 0;
+		if( left == 0 )
+			return -1;
+		if( len > left )
+			len = (int)left;
+		int n = super.read(b,off,len);
+		if( n == -1 )
+			throw new EOFException();
+		left -= n;
+		return n;
+	}
+
+	public synchronized long skip(long n) throws IOException {
+		if( n > left )
+			n = left;
+		n = in.skip(n);
+		left -= n;
+		return n;
+	}
+
+	public synchronized int available() throws IOException {
+		int n = in.available();
+		if( n > left )
+			n = (int)left;
+		return n;
+	}
+
+	public void mark(int readlimit) {}
+
+	public void reset() throws IOException {
+		throw new IOException("not supported");
+	}
+
+	public boolean markSupported() {
+		return false;
+	}
+
+}