views:

336

answers:

6

I have a set of source folders. I use a Java class to build the distribution file out of these folders. I'd like to write another little class in Java which runs every half a second, checks if any of the files in the folders have changed, and if yes, run the building class.

So, how do I detect easily that a folder has been modified ?

+1  A: 

If you can are allowed to use Java 7, it has support for platform independent directory/file change notifications.

JNA has a sample for cross platform change notification here. Not sure how easy you might find it.

kd304
+1  A: 

I think you will need to check the directory and subdirectory modfication times (for files being added/removed) and the file modification times (for the changes in each file).

Write a recursive routine that checks a directory for it's modification time and if it's changed, plus each files. Then checks the directory contents, and call recursively for any subdirectories. You should just be able to check for any modification times greater than when you last ran the check.

See File.lastModified()

Brian Agnew
+1  A: 

I don't know if it's any good, but here's one person's take on the problem.

Sounds like .NET has something built-in: FileSystemWatcher

UPDATE: Thanks to kd304, I just learned that Java 7 will have the same feature. Won't do you much good today, unless you can use the preview release.

duffymo
A: 

with NIO2 (Java7) it will be very easy. With Java6 you could call list() and compare with previous list once a second? (a poor man watching service)

dfa
+1  A: 

You need to watch each file and keep track of the File.lastModified attribute and check the File.exists flag together with a bit of simple recursion to walk the directory structure.

Nick Holt
+1  A: 

Here a list of possible solutions and an example of simple File/Folder Watcher.

RealHowTo