Skip to content

Java: Creating a Stream on a ByteBuffer

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;

One Trackback/Pingback

  1. [...] 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 *


E-mail It