Monday, August 15, 2016

Use InputStream.available() with caution

You might assume that InputStream.available() returns how many bytes are available to be read from your stream. And you'd be almost right; it's really how many bytes are guaranteed to be available, not how many are actually available. 

Okay, to get to specifics, my problem occurred when I used a ZipInputStream wrapped around a file. I (stupidly) assumed that all the bytes must be available, since it's a file sat on my computer. However, since ZipInputStream reads a compressed file, the number of bytes available isn't the same as the original file size. (I should mention that at this point I didn't actually know I was reading a zipped file, as the whole point of streams is that you don't normally need to bother yourself with the implementation).

In addition, ZipInputStream.available() only returns either 1 or 0, so it would be unwise to use that size as the basis for an array to ready the data in.

So, my point is, available() should really be [treated as] a boolean.  If it's > 0, great, you can read something.  Just don't put any reasoning behind the actual number.



No comments: