KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > media > util > ByteBufferUtils


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7
8 package org.jboss.media.util;
9
10 import java.io.IOException JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.io.OutputStream JavaDoc;
13 import java.nio.ByteBuffer JavaDoc;
14
15 /**
16  * This class implements methods for creating an input or output stream on a ByteBuffer.
17  *
18  * <p>Obtain or create a ByteBuffer:
19  * <pre>ByteBuffer buf = ByteBuffer.allocate(10);</pre>
20  *
21  * <p>Create an output stream on the ByteBuffer:
22  * <pre>OutputStream os = newOutputStream(buf);</pre>
23  *
24  * <p>Create an input stream on the ByteBuffer:
25  * <pre>InputStream is = newInputStream(buf);</pre>
26  *
27  * @version <tt>$Revision: 1.1 $</tt>
28  * @author <a HREF="mailto:ricardoarguello@users.sourceforge.net">Ricardo Argüello</a>
29  */

30 public class ByteBufferUtils
31 {
32    /**
33     * Returns an output stream for a ByteBuffer.
34     * The write() methods use the relative ByteBuffer put() methods.
35     */

36    public static OutputStream JavaDoc newOutputStream(final ByteBuffer JavaDoc buf)
37    {
38       return new OutputStream JavaDoc()
39       {
40          public synchronized void write(int b) throws IOException JavaDoc
41          {
42             buf.put((byte) b);
43          }
44
45          public synchronized void write(byte[] bytes, int off, int len)
46             throws IOException JavaDoc
47          {
48             buf.put(bytes, off, len);
49          }
50       };
51    }
52
53    /**
54     * Returns an input stream for a ByteBuffer.
55     * The read() methods use the relative ByteBuffer get() methods.
56     */

57    public static InputStream JavaDoc newInputStream(final ByteBuffer JavaDoc buf)
58    {
59       return new InputStream JavaDoc()
60       {
61          public synchronized int read() throws IOException JavaDoc
62          {
63             if (!buf.hasRemaining())
64             {
65                return -1;
66             }
67             return buf.get();
68          }
69
70          public synchronized int read(byte[] bytes, int off, int len)
71             throws IOException JavaDoc
72          {
73             // Read only what's left
74
len = Math.min(len, buf.remaining());
75             buf.get(bytes, off, len);
76             return len;
77          }
78       };
79    }
80 }
81
Popular Tags