View Javadoc

1   /**********************************************************************
2    * ChannelInputStream.java
3    * created on 16.08.2004 by netseeker
4    * $Source: /cvsroot/ejoe/EJOE/src/de/netseeker/ejoe/io/ByteBufferInputStream.java,v $
5    * $Date: 2006/02/04 14:15:52 $
6    * $Revision: 1.5 $
7    *********************************************************************/
8   
9   package de.netseeker.ejoe.io;
10  
11  import java.io.InputStream;
12  import java.nio.ByteBuffer;
13  
14  /***
15   * Implements an input stream over a NIO ByteBuffer. The ByteBuffer is
16   * replacable, and is supplied by an external source. This class is based on an
17   * article found at the homepage of Michael W. Spille.
18   * 
19   * @author Michael W. Spille
20   * @author netseeker aka Michael Manske
21   * @link http://www.krisnmike.com/mike/nio.html
22   */
23  public class ByteBufferInputStream extends InputStream
24  {
25  	private ByteBuffer	buffer;
26  
27  	/***
28  	 * Constructs a new ByteBufferInputStream which reads from specified buffer
29  	 */
30  	public ByteBufferInputStream(ByteBuffer buffer)
31  	{
32  		this.buffer = buffer;
33  	}
34  
35  	/***
36  	 * @param buffer
37  	 */
38  	public void setByteBuffer(ByteBuffer buffer)
39  	{
40  		this.buffer = buffer;
41  	}
42  
43  	/*
44  	 * (non-Javadoc)
45  	 * 
46  	 * @see java.io.InputStream#available()
47  	 */
48  	public int available()
49  	{
50  		return (buffer.remaining());
51  	}
52  
53  	/*
54  	 * (non-Javadoc)
55  	 * 
56  	 * @see java.io.InputStream#close()
57  	 */
58  	public void close()
59  	{
60  	}
61  
62  	/*
63  	 * (non-Javadoc)
64  	 * 
65  	 * @see java.io.InputStream#markSupported()
66  	 */
67  	public boolean markSupported()
68  	{
69  		return (false);
70  	}
71  
72  	/*
73  	 * (non-Javadoc)
74  	 * 
75  	 * @see java.io.InputStream#read()
76  	 */
77  	public int read()
78  	{
79  		if (buffer.hasRemaining())
80  		{
81  			return (buffer.get() & 0xff);
82  		}
83  		else
84  		{
85  			return (-1);
86  		}
87  	}
88  
89  	/*
90  	 * (non-Javadoc)
91  	 * 
92  	 * @see java.io.InputStream#read(byte[])
93  	 */
94  	public int read(byte[] b)
95  	{
96  		return (read(b, 0, b.length));
97  	}
98  
99  	/*
100 	 * (non-Javadoc)
101 	 * 
102 	 * @see java.io.InputStream#read(byte[], int, int)
103 	 */
104 	public int read(byte[] b, int offset, int length)
105 	{
106 		if (!buffer.hasRemaining())
107 		{
108 			return (-1);
109 		}
110 		if (length > buffer.remaining())
111 		{
112 			length = buffer.remaining();
113 		}
114 		buffer.get(b, offset, length);
115 		return (length);
116 	}
117 }