posted 17 years ago
[Paul C]: And it's unlikely that your first call to is.read() is actually going to read the entire upload, if the content length is fairly large, and your code arbitrarily rejects that too.
I don't believe that's true here - Aaron's code does seem to keep reading until either the content length is reached, or an EOF is returned. Assuming the content length is set correctly (not always true, as noted) then it will never actually read the EOF. Still, I agree with all your other points.
[Aaron]: How does specifying a fixed buffer size help here, especially when you have a big file to read and write?
The primary benefit is as Paul noted - it uses less memory (at least for large files) because you don't have to store the entire file in memory at once. Also most IO doesn't occur all at once anyway - the servlet is probly getting the request data in chunks, as it receives packets, and the FileOutputStream may well be writing in chunks too as limited by a hardwaree buffer somewhere. The idea here is to grab whatever data is available, as soon as it's available, and transfer it - rather than waiting for all the data to become available. Thus this is generally a little more efficient, doing some disk writing while the network is still transferring bytes to the server.
One other thing: I usually recommend putting all close() operations in a finally block. This ensures that a stream is closed promptly even if an exception occurs. This doesn't really matter, say, 99% of the time or more, but in the remaining 1% or so it can help prevent some confusing errors. Especially if you plan to move or delete any files when you're done with them - an open FileInputStream or FileOutputStream can cause delete() or renameTo() to fail inexplicably. (That is, it's explicable only if you realize that there's an unclosed stream somewhere.) These are a pain to debug, and so I usually am very religious about making sure streams get closed after they're used. So my version of this code would be:
"I'm not back." - Bill Harding, Twister