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. We need your name and email address only for verifying a legitimate comment. For more information, a copy of your saved data or a request to delete any data under this address, please send a short notice to michael@simons.ac from the address you used to comment on this entry.
By entering and submitting a comment, wether with or without name or email address, you'll agree that all data you have entered including your IP address will be checked and stored for a limited time by Automattic Inc., 60 29th Street #343, San Francisco, CA 94110-4929, USA. only for the purpose of avoiding spam. You can deny further storage of your data by sending an email to support@wordpress.com, with subject “Deletion of Data stored by Akismet”.
Required fields are marked *