Top.Mail.Ru
July 27th, 2007 - Java developers — LiveJournal
? ?

Java developers

July 27th, 2007
 

10:18 am - ex_juan_gan - global warning regarding stream.read()

I am sure many people read the documentation and know that Java does not guarantee that read() operation on a stream returns as much data as you specify, even if the file (stream) does have the data. This is wrong.
" An attempt is made to read as many as len bytes, but a smaller number may be read, possibly zero" You cannot even count on reading stream.available() number of bytes.

On a recent Puzzler Talk Josh Bloch did show a good example where a similar assumption leads to a miserable failure.

Unfortunately, not everyone knows this. If you look around, you'll find cases where people either

* allocate a buffer for the whole file size, and call read() without bothering to check if they did read everything
* allocate a buffer, read the stream, check the result, and if it is not equal to expected, scream and run

Both behaviors are wrong. It happens in real life that not the whole contents of a stream is returned in one operation; so the right behavior would be to read until the end of the stream.

(If you are interested in using a ready solution, check out Files.java class in myjavatools.com - and you have to believe me that "advertising" this site is not the purpose of this posting. I just want to see more reliable software around, and I don't care whether you use my code, just copy and paste it, or write your own.)
Powered by LiveJournal.com