Reputation: 1522
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.
Upvotes: 13
Views: 3088
Reputation: 1565
It depends on how the write fails, but the InterruptedIOException may be what you're looking for:
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/InterruptedIOException.html
It contains a field for "bytesTransferred": "Reports how many bytes had been transferred as part of the I/O operation before it was interrupted."
Upvotes: 1
Reputation: 340993
You can't, IOException
can happen at any time. If you think about it, IOException
can 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.
Upvotes: 6