Check out this link:
Copying One File to Another | Example Depot
As you can see it gives a simple example as to how to copy a file with java. The third comment by user "Jooce" however mentions a buffer underflow issue. So what's the exact behaviour of read() ? Isn't it supposed to fill its argument buffer until it's either full or the end of file has been reached?
If no, what's the safest practice in order to avoid these kind of issues? (especially when your source of data is some kind of internet socket...)
1 reply to this topic
#1
Posted 14 May 2011 - 12:27 PM
|
|
|
#2
Posted 14 May 2011 - 01:49 PM
Well just using >=0 as he mentioned should be safe enough.
It returns 0 if there were no bytes send over (sendedBytes = new Byte[0]), know that the buffer underrun occurs when the client(receiver) is able to process much faster than the server(sender) can send.
If for example the server is sending at 10kB / s, and the client is receiving and processing at 20kB/s, there can/will be times the client will receive 0 bytes, just because the server can't send fast enough.
The code you found there would then close the connection because there were 0 bytes read, but in fact you should keep on trying if the returned value is 0. Only -1 indicates the whole file is send trough.
Flushing the outpustream lastly, is required to make sure the file is written completely. The outputstream is able to not immediately write away everything, but hold the bytes in its internal buffer a while.
If you would just close your stream, there is a chance that some bytes were still left in its buffer and not yet written to the file. Calling flush forces the stream to write all its remaining bytes to the file.
using >=0 and flush() should be safe enough.
It returns 0 if there were no bytes send over (sendedBytes = new Byte[0]), know that the buffer underrun occurs when the client(receiver) is able to process much faster than the server(sender) can send.
If for example the server is sending at 10kB / s, and the client is receiving and processing at 20kB/s, there can/will be times the client will receive 0 bytes, just because the server can't send fast enough.
The code you found there would then close the connection because there were 0 bytes read, but in fact you should keep on trying if the returned value is 0. Only -1 indicates the whole file is send trough.
Flushing the outpustream lastly, is required to make sure the file is written completely. The outputstream is able to not immediately write away everything, but hold the bytes in its internal buffer a while.
If you would just close your stream, there is a chance that some bytes were still left in its buffer and not yet written to the file. Calling flush forces the stream to write all its remaining bytes to the file.
using >=0 and flush() should be safe enough.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









