user3086314
user3086314

Reputation: 31

file.lastModified() function does not give the updated value

file.lastModified() not updated , although I change the file content , I work on Windows.
I use File of java , what could be the problem ? Do I need to do some kind of refresh from the code ?

Upvotes: 3

Views: 3470

Answers (4)

DevDio
DevDio

Reputation: 1564

If the file was loaded from the classpath resources, files.lastModified() might not detect the change after an edit is made. However, when the file was loaded from the outside of the application, it did work well in my case (Windows 10, Java 10).

I've tested it by running files.lastModified() on a scheduled thread, the file reference was loaded once at the JVM startup.

So depending on how your file is loaded, it might affect how file modification is read.

Upvotes: 1

David Bradley
David Bradley

Reputation: 196

Java, at least 1.8 appears to be caching file attributes. I created a C++ application that uses the Win32's FindFirstFile to get the file information and verify that the last modified value is updated every time. And it does. But Java's File and Files both seem to not always get the latest value. Even tried a one second delay between writes and it didn't always get updated. I'm using Files.write to modify the file so I would hope it's closing it. Not sure if there's a good solution for this in Java, which is unfortunate.

UPDATE:

I found that Files.getLastModifiedTime is a solution for this. But it's only available for Java 1.8 or later.

Upvotes: 4

user207421
user207421

Reputation: 310926

This behaviour is platform-dependent. Windows doesn't update the metadata of a file being modified until it is closed.

Upvotes: 2

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

If you are setting lastModified time. it should work fine

 File file =new File("fileName");
 // other operations
 file.setLastModified(new Date().getTime()); // set time

Now you can get lastUpdated time back.

file.lastModified();

Upvotes: 0

Related Questions