01: /*
02: * @(#)ByteBufferInputStream.java 1.2 04/12/06
03: *
04: * Copyright (c) 2001-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.nio;
10:
11: import java.io.InputStream;
12: import java.io.IOException;
13: import java.io.EOFException;
14: import java.nio.ByteBuffer;
15: import java.nio.BufferUnderflowException;
16:
17: public class ByteBufferInputStream extends InputStream {
18: private ByteBuffer buffer;
19: private int mark;
20: private boolean eof;
21:
22: public ByteBufferInputStream(ByteBuffer buf) {
23: this .buffer = buf;
24: }
25:
26: public int read() throws IOException {
27: if (eof) {
28: throw new EOFException();
29: }
30: try {
31: return (int) buffer.get();
32: } catch (BufferUnderflowException e) {
33: eof = true;
34: return -1;
35: }
36: }
37:
38: public int read(byte[] b, int offset, int size) throws IOException {
39: if (eof) {
40: throw new EOFException();
41: }
42: int oldPosition = buffer.position();
43: int limit = buffer.limit();
44: if (limit == oldPosition) {
45: eof = true;
46: return -1;
47: }
48: if (size > limit - oldPosition) {
49: size = limit - oldPosition;
50: }
51: try {
52: buffer.get(b, offset, size);
53: return buffer.position() - oldPosition;
54: } catch (IndexOutOfBoundsException e1) {
55: throw new IOException(e1.getMessage());
56: } catch (BufferUnderflowException e2) {
57: throw new IOException(e2.getMessage());
58: }
59: }
60:
61: public long skip(long n) throws IOException {
62: if (eof) {
63: throw new EOFException();
64: }
65: int oldPosition = buffer.position();
66: int limit = buffer.limit();
67: long newPosition = oldPosition + n;
68: if (newPosition > limit) {
69: newPosition = limit;
70: }
71: buffer.position((int) newPosition);
72: return newPosition - oldPosition;
73: }
74:
75: public int available() throws IOException {
76: return buffer.remaining();
77: }
78:
79: public void close() throws IOException {
80: }
81:
82: public void mark(int readlimit) {
83: mark = buffer.position();
84: }
85:
86: public void reset() throws IOException {
87: buffer.position(mark);
88: }
89:
90: public boolean markSupported() {
91: return true;
92: }
93: }
|