>> M.J. Dance wrote:
>>>byte[] bytes = new byte[file.length()];
>>>in.read(bytes);
>Chris Uppal wrote:
>> /NEVER/ do that. Never !
Thomas Fritsch <> wrote:
>It should be replaced by something like this:
>
> byte[] bytes = new byte[file.length()];
> for (int n = 0, x; n < bytes.length; n += x ) {
> x = in.read(bytes, n, bytes.length - n);
> if (x < 0)
> throw new EOFException("stream shorter than expected");
> }
As long as you're checking for files that got shorter between creating your
byte array and actually reading, you might want to check that it got longer
with in.available() or just by reading another byte and seeing if one's there.
Alternately, you may prefer to just read whatever you can and not trust the
file.length() call at all. This works even if you're not reading from a file
(like from getResourceAsStream() or a network stream).
// best-guess starting size, make it up if we don't have a file.
ByteArrayOutputStream baos = new ByteArrayOutputStream(file.length());
byte[] buf = new byte[1024]; // read up to 1k at a time
boolean done=false;
while (!done) {
int amtRead = in.read(buf);
if (amtRead == -1) {
done = true; // EOF
} else {
baos.write(buf, 0, amtRead);
}
}
byte[] bytes = baos.toByteArray();
--
Mark Rafn
<http://www.dagon.net/>