Creating a Stream on a ByteBuffer

This example implements methods for creating an input or output stream on a ByteBuffer.
// Obtain a ByteBuffer; see Creating a ByteBuffer. ByteBuffer buf = ByteBuffer.allocate(10); // Create an output stream on the ByteBuffer OutputStream os = newOutputStream(buf); // Create an input stream on the ByteBuffer InputStream is = newInputStream(buf); // Returns an output stream for a ByteBuffer. // The write() methods use the relative ByteBuffer put() methods. public static OutputStream newOutputStream(final ByteBuffer buf) { return new OutputStream() { public synchronized void write(int b) throws IOException { buf.put((byte)b); } public synchronized void write(byte[] bytes, int off, int len) throws IOException { buf.put(bytes, off, len); } }; } // Returns an input stream for a ByteBuffer. // The read() methods use the relative ByteBuffer get() methods. public static InputStream newInputStream(final ByteBuffer buf) { return new InputStream() { public synchronized int read() throws IOException { if (!buf.hasRemaining()) { return -1; } return buf.get(); } public synchronized int read(byte[] bytes, int off, int len) throws IOException { // Read only what's left len = Math.min(len, buf.remaining()); buf.get(bytes, off, len); return len; } }; }

Comments

1 Apr 2010 - 10:33am by Anonymous (not verified)

Thanks!

15 Apr 2010 - 11:07am by Anonymous (not verified)

There is a bug in this code. In InputStream.read, need to return (int)(buf.get() & 0xFF);

Java converts a byte to a signed int by default, so any values over 127 will be wrong.

27 Apr 2010 - 2:26pm by Anonymous (not verified)

there is an error in the read method, according to the javadocs it must return -1 so it should be:

public synchronized int read(byte[] bytes, int off, int len) throws IOException {

if (!buf.hasRemaining()) {
return -1;
}

// Read only what's left
len = Math.min(len, buf.remaining());
buf.get(bytes, off, len);
return len;
}

:) this popped up when we tried to load jpg images! png worked fine... but jpg only worked after the fix.

Cheers

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.