Search code examples
javajnotify

Using the JNotify library, how can you tell if a deleted file was a file or a directory?


For those unfamiliar with JNotify, this is a library which provides an easy way to monitor events in a directory.

For instance, when a file gets deleted in the selected folder, the method "fileDeleted" gets called, along with a few parameters. Here's an example of the fileDeleted method:

public void fileDeleted(int wd, String rootPath, String name) {
   print("deleted " + rootPath + " : " + name);
}

Now, I would like to know if the deleted file was a file or directory. My usual approach is to create a new File object with the given path, and use the methods isFile() and isDirectory()

However, since this file is already deleted, these methods always return false.

So here's my concrete question: I have the path to a deleted file or directory, how can I tell wether it was a file or a directory? Is there a workaround to this? What's the best practice to do here?

Thank you in advance.


Solution

  • I suggest using a better API for this, like Commons IO. It has this distinction in its interface org.apache.commons.io.monitor.FileAlterationListener and its methods onFile...(), onDirectory...(). Alternatively, and this is probably the best approach, use the new standard feature for this that comes with Java 7, WatchService, as discussed here.