My app writes loads of bytes constantly to a file. If a block of my code is writing out bytes and gets an IOException if the connection to the drive or network is lost how am I to know how many bytes it has written?
For eg I’m writing 2500 bytes at a time and if an IOException occurs does it mean it wrote nothing to the file or it would have written partial bytes to the file? If partial bytes are written to the file how am I to know how much is written
FYI I’m using
DataOutputStream
to write out files. I flush only when my app closes.
You can’t,
IOExceptioncan happen at any time. If you think about it,IOExceptioncan be caused by software or hardware failure at any time, before the first byte was written, after all were written but something happened to the connection – or in the middle if the data chunk was pretty big.After reconnecting you must check the file size or use some other technique to keep files in consistent state and recover. The simplest safety net: read file size before writing data and store it reliably, write the data and read file size after writing. If error occurrs and current file size is not equal to expected file size (last saved), truncate extra bytes and retry.
Read about transaction logs in relational databases to see how big and reliable software handles such cases.