0

I write current date time to a file (file may already exist or not) as content of the file. Later, I compare the date modified time of the file with the date time included in the file as content. However, date modified time is less than content date time. How can something that happened later (date modified time of the file) have a earlier time. Data content is json string, written as a text file. (note that: I don't set date modified time programmatically)

Here is my code

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//this is how file content is formatted for writing.
writeFile(location, dateFormat.format(new Date()))


public static void writeFile(String location, String data) {
    try {
        PrintWriter output = new PrintWriter(
                new File(location));
        output.write(data);
        output.close();
    } catch (FileNotFoundException e) {

    }
}

 **To compare**
 //read content from file
 Date date = dateFormat.parse(dateString);
 //get file modified time
 Date diskTime = new Date(file.lastModified());

 if(this.diskTime.getTime() < this.contentTime.getTime()
                        || (this.diskTime.getTime() -   this.contentTime.getTime()) > 2500)
  {
       return false;
  }

The issue is diskTime sometimes (not always) a second before content time so above if case returns false.

Does this happen normally and how to overcome (create file always)?

Narendra Singh
  • 3,990
  • 5
  • 37
  • 78
pats
  • 1,273
  • 2
  • 20
  • 43

1 Answers1

0

Unfortunately, Android lastModified value has been reported unreliable as it utilizes internal cache and also has a bug. you can read related answer for this issue.

And this post author tried similar experiments you did. If you plan to check file modification time, I recommend to manage timestamp at another data storage like SqlLite.

Community
  • 1
  • 1
Youngjae
  • 24,352
  • 18
  • 113
  • 198
  • Thanks for ur response. I am not setting last modified time though I am just writing to the file and hope android would update the modified time. Do you think if I recreate the file always that might resolve the problem. – pats Jun 04 '15 at 10:14
  • @pats // I mean not only `setLastModified` method but also modified time itself is not reliable. – Youngjae Jun 04 '15 at 13:18