0

Is it possible to roll back the current IO operation incase of any exceptions during writing? I'm trying to write a UTF-8 string to a file with Okio library using the below expression

file.sink().buffer().writeUtf8(fileContent).close()

It works for normal cases. But if an exception occurs during writing, it just writes an empty string to a file overwriting the existing one.

I know I can backup the old content before writing and overwrite in the catch block incase of exceptions. But it looks like a common problem and I'm wondering if there are any alternative solutions available for the same.

Thanks!

Vijay
  • 545
  • 1
  • 5
  • 15
  • you could read the file before overwriting since you're writing not appending. So the old data maybe lost! – Animesh Sahu Apr 23 '20 at 08:53
  • @AnimeshSahu Yes as I said in my question, we can do that. But it looks tedious work because exceptions are common during IO. I'm wondering if there are any alternate solutions available without writing boilerplate code. – Vijay Apr 23 '20 at 09:17
  • IIRC there's no possible way since the file was going to be overridden, bytes are going to be replaced, incomplete meta-data of file will interpret it as empty in usual file viewer, you'd try using some 3rd party recovery software to check if there is some data saved inside it. – Animesh Sahu Apr 23 '20 at 09:23
  • The only other approach would be to collect the data but _not_ open or write to the file itself until all the data had been collected successfully. But that could take a lot of memory if the file will get big. – gidds Apr 24 '20 at 07:12

1 Answers1

0

Depending on the platform, you can use an Atomic File to ensure data integrity.

If there is no support on the platform for an Atomic File, you can build something out to replace the old file after successful write.

This is an expensive operation, though.

Here's Android's AtomicFile class:

https://developer.android.com/reference/android/util/AtomicFile

05nelsonm
  • 311
  • 3
  • 5