views:

369

answers:

2

I have a button that I want to disable as long as there isn't a specific number of files in a directory. Is there some kind of listener that notifies me at the moment a file is created or deleted in a directory?

+4  A: 

There's no current native support in Java for file system events and monitoring. JNotify is a useful library for doing this. You should set it up to monitor the directory for modifications, and then determine yourself what's been added/removed.

Java 7 will have file system event support built into it.

Brian Agnew
+3  A: 

One thing you might want to consider - If you're listening for creation events then you'll want to make sure that the file is completely written before you start reading it. I'm not sure what type of support Java 7 will offer for this problem.

I've implemented mechanisms like this in the past and this particular problem required special handling. If you are controlling both the file reader and writer then you can get around this with naming conventions, etc. (the writer names the file xxx.prt and renames the file when it's done being written). Since I didn't have control of the writer I had to add another polling mechanism to check the file size on an interval to make sure each new file was actually ready to be read. Not a perfect solution, but was sufficient for my case.

My two cents...

tyler