0bcbe14ec89a96a26cf56933ef94aef3214cd1a4
[nikiroo-utils.git] / src / be / nikiroo / utils / NextableInputStream.java
1 package be.nikiroo.utils;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 public class NextableInputStream extends InputStream {
7 private InputStream in;
8 private boolean eof;
9 private int pos = 0;
10 private int len = 0;
11 private byte[] buffer = new byte[4096];
12
13 public NextableInputStream(InputStream in) {
14 this.in = in;
15 }
16
17 @Override
18 public int read() throws IOException {
19 preRead();
20 if (eof) {
21 return -1;
22 }
23
24 return buffer[pos++];
25 }
26
27 @Override
28 public int read(byte[] b) throws IOException {
29 return read(b, 0, b.length);
30 }
31
32 @Override
33 public int read(byte[] b, int boff, int blen) throws IOException {
34 if (b == null) {
35 throw new NullPointerException();
36 } else if (boff < 0 || blen < 0 || blen > b.length - boff) {
37 throw new IndexOutOfBoundsException();
38 } else if (blen == 0) {
39 return 0;
40 }
41
42 int done = 0;
43 while (!eof && done < blen) {
44 preRead();
45 for (int i = pos; i < blen && i < len; i++) {
46 b[boff + done] = buffer[i];
47 pos++;
48 done++;
49 }
50 }
51
52 return done > 0 ? done : -1;
53 }
54
55 private void preRead() throws IOException {
56 if (in != null && !eof && pos >= len) {
57 pos = 0;
58 len = in.read(buffer);
59 // checkNexts();
60 }
61
62 if (pos >= len) {
63 eof = true;
64 }
65 }
66 }