• Post Reply Bookmark Topic Watch Topic
  • New Topic

BufferedInputStream.read method

 
Wes B Webster
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please take a look at the code below. I am trying to use the the BufferedInputStream.read method to read in an image, but it keep erroring out on the last read rather then reading the remaining bytes and returning that number. I can't figure out why the method isn't working. I have worked around it by reading a byte at a time, but I figured that my code would be more optimized if I were to use the byte array as in the code below.

============ code that doesn't work but seemingly should ======================
BufferedInputStream gifData =
new BufferedInputStream(rs.getBinaryStream("pic"));

int b;
int c=0;

byte[] buf = new byte[1 * 1024]; // 4K buffer
int len;

while ((len = gifData.read(buf, 0, buf.length))!= -1)
{
System.out.println("about to read buf");
out.write(buf, 0, len);
c+= len;
System.out.println(c);
}

====== this is the output of the above
about to read buf
1024
about to read buf
2048
about to read buf
3072
about to read buf
4096
about to read buf
5120
about to read buf
6144
about to read buf
7168
java.io.IOException




============== code that does work ======================
BufferedInputStream gifData =
new BufferedInputStream(rs.getBinaryStream("pic"));

int b;
int c=0;


while ((b = gifData.read()) != -1)
{
out.write(b);
c++;

}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strange. I use code like this all the time; it should work. It may help if you show the full text of the exception including stack trace. Also, I usually use a slightly simpler form

This method automatically starts at offset 0 and reads no more bytes than the array can hold. So it should work exactly the same as the code you showed - but it might be worthwhile to see if it makes any difference.
Since you're getting this InputStream from a ResultSet, there's a decent chance it's an implementation provided by your database driver. Possibly this implemenation has a bug, and you might be able to fix this by using a different driver, or updating the one you have. Try getting more info on the implementation used:

If the package name of the InputStream class indicates it's from whatever company made the DB driver you're using, that tells you it's worthwhile to check that company's user support site to see if there are any bug reports / workarounds / updated drivers. Or try a completely different driver, if available.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!