comparison 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
comparison
equal deleted inserted replaced
1489:fe237d72b234 1490:9a2a2181a58f
1 package goodjava.io;
2
3 import java.io.InputStream;
4 import java.io.FilterInputStream;
5 import java.io.IOException;
6 import java.io.EOFException;
7
8
9 public class FixedLengthInputStream extends FilterInputStream {
10 protected long left;
11
12 public FixedLengthInputStream(InputStream in, long len) {
13 super(in);
14 if( len < 0 )
15 throw new IllegalArgumentException("len can't be negative");
16 this.left = len;
17 }
18
19 public synchronized int read() throws IOException {
20 if( left == 0 )
21 return -1;
22 int n = super.read();
23 if( n == -1 )
24 throw new EOFException();
25 left--;
26 return n;
27 }
28
29 public synchronized int read(byte[] b, int off, int len) throws IOException {
30 if( len == 0 )
31 return 0;
32 if( left == 0 )
33 return -1;
34 if( len > left )
35 len = (int)left;
36 int n = super.read(b,off,len);
37 if( n == -1 )
38 throw new EOFException();
39 left -= n;
40 return n;
41 }
42
43 public synchronized long skip(long n) throws IOException {
44 if( n > left )
45 n = left;
46 n = in.skip(n);
47 left -= n;
48 return n;
49 }
50
51 public synchronized int available() throws IOException {
52 int n = in.available();
53 if( n > left )
54 n = (int)left;
55 return n;
56 }
57
58 public void mark(int readlimit) {}
59
60 public void reset() throws IOException {
61 throw new IOException("not supported");
62 }
63
64 public boolean markSupported() {
65 return false;
66 }
67
68 }