Java: Creating a Stream on a ByteBuffer

October 18, 2007 by Michael

This example is plain wrong. The InputStream will cause an endless loop as it always returns a value >= 0. Working code as follows:

private static InputStream _newInputStream(final ByteBuffer buf) {
	return new InputStream() {
		public synchronized int read() throws IOException {				
			return buf.hasRemaining() ? buf.get() : -1;
		}
 
		public synchronized int read(byte[] bytes, int off, int len) throws IOException {			
			int rv = Math.min(len, buf.remaining());				
			buf.get(bytes, off, rv);
			return rv == 0 ? -1 : rv;
		}
	};
}

No comments yet

One Trackback/Pingback
  1. A fistfull of readers | info.michael-simons.eu on October 23, 2007 at 4:07 PM

    […] presenting a working InputStream on a ByteBuffer, i have to more readers for you out […]

Post a Comment

Your email is never published nor shared. Required fields are marked *