1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.beep4j.internal.util;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.nio.ByteBuffer;
21
22
23
24
25
26
27 public class ByteBufferInputStream extends InputStream {
28
29
30
31
32 private ByteBuffer buffer;
33
34
35
36
37
38
39
40
41
42 public ByteBufferInputStream(ByteBuffer buffer) {
43 Assert.notNull("buffer", buffer);
44 this.buffer = buffer.asReadOnlyBuffer();
45 }
46
47
48
49
50 private void checkClosed() throws IOException {
51 if (buffer == null) {
52 throw new IOException("stream is closed");
53 }
54 }
55
56 @Override
57 public boolean markSupported() {
58 return true;
59 }
60
61 @Override
62 public synchronized void mark(int readlimit) {
63 if (buffer != null) {
64 buffer.mark();
65 }
66 }
67
68 @Override
69 public synchronized void reset() throws IOException {
70 checkClosed();
71 buffer.reset();
72 }
73
74 @Override
75 public int read() throws IOException {
76 checkClosed();
77 return buffer.hasRemaining() ? buffer.get() : -1;
78 }
79
80 @Override
81 public int read(byte[] b) throws IOException {
82 return read(b, 0, b.length);
83 }
84
85 @Override
86 public int read(byte[] b, int off, int len) throws IOException {
87 checkClosed();
88 int length = Math.min(available(), len);
89 if (length == 0) {
90 return -1;
91 } else {
92 buffer.get(b, off, length);
93 return length;
94 }
95 }
96
97 @Override
98 public int available() throws IOException {
99 checkClosed();
100 return buffer.remaining();
101 }
102
103 @Override
104 public void close() throws IOException {
105 buffer = null;
106 }
107
108 }