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;
}
};
}
Share This
— Trackback URI
This entry (permalink) was posted on Thursday, October 18, 2007, at 11:19 am by Michael, tagged with Code Snippets, Java, Tipps and categorized in Java, Shortcuts.
The following post could be of some interest: A fistfull of readers, Old and tired?, The dangers of Javas ImageIO, All roads lead to Rome…, Using rubyzip to create zip files on the fly, Apache httpd, Tomcat und sendfile, Linux: Persistent wake-on-lan, Installing Oracle VM Server, Editing muxed mpeg1 and mpeg2 files for free on the mac, On writing binary data from within Oracle Forms 6i
One Trackback/Pingback
[...] presenting a working InputStream on a ByteBuffer, i have to more readers for you out [...]
Post a Comment