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
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)...
— 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, Java 7, JAAS and Kerberos Single Sign-on vs. newer Windows Systems, Using rubyzip to create zip files on the fly, All roads lead to Rome…, Linux: Persistent wake-on-lan, Apache httpd, Tomcat und sendfile, Editing muxed mpeg1 and mpeg2 files for free on the mac, Installing Oracle VM Server
One Trackback/Pingback
[...] presenting a working InputStream on a ByteBuffer, i have to more readers for you out [...]
Post a Comment