Search code examples
javaandroidfilefileutils

Android File.length() returns 0 while writing to it


I have a log file in my app that is constantly being written to and sometimes i need to check its size. The problem is that whenever i check its size quickly in another thread it sometimes returns 0, even though there is clearly data in it.

For example the file size output would look something like this: (numbers are bytes)

E/DataLogger: Size: 3403
E/DataLogger: Size: 3454
E/DataLogger: Size: 3454
E/DataLogger: Size: 3454
E/DataLogger: Size: 0
E/DataLogger: Size: 3500
E/DataLogger: Size: 3500
E/DataLogger: Size: 3812

I also tried with FileUtils.readFileToByteArray() and noticed the same behavior. Why do both these methods randomly return 0 sometimes?


Solution

  • It turns out I was occasionally overwriting the file, which briefly set the file size to 0 before new data could be written.