views:

79

answers:

3

I have a directory of files that I need to check for changes. I consider it changed when one of the files has a modifiedDate newer than what I remembered from the last check (this is meant to be a cache dependency).

What would be the fastest way of finding the latest modified file in a directory in Java?


Maybe I'm too optimistic, but I'm explicitly looking for something that does not involve iterating all the files.

Also, checking the directory modified date is not enough, as this only changes when the list of files inside changes, not when one of the files themselves is just modified.

+1  A: 

You must iterate all file names and extract the modification date.

darko petreski
+1  A: 

Even if you're not looking to iterate all of the files, any third-party API you use to find this will iterate all of the files.

JDK 7 is intended to have java.nio.WatchService, which will apparently iterate through everything if it has to, but will use filesystem support to do exactly what you've asked for. On the minus side, that's still in the future.

Dean J
I already thought so. I guess this is what I will end up doing.
Tomalak
Actually, the future has something shiny. Let me edit my answer.
Dean J
@Dean J: Thanks for the edit. :-) PS: Something like this is doable in .NET already (via `System.IO.FileSystemWatcher`).
Tomalak
I'm very much looking forward to JDK 7 - if and when it's actually done - as Java has some catchup to do with things C# devs now take for granted.
Dean J
A: 

I think that is not possible. You can use an Runtime class to exec an unix command line from java "ls -lrt | tail -1" and parse the string to get the name of the latest modified file

zoomer.hammerball
I refer not possible without walking by all the file objects in the directory
zoomer.hammerball
If you have several thousand files (and some day probably you will have) this is not good idea.
darko petreski