Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java7 WatchService - Access Denied error trying to delete recursively watched nested directories (Windows only)

I followed the Watching a Directory for Changes Java7 nio2 tutorial to recursively monitor the entire contents of a directory using the code sample WatchDir.java.

While this works well on Linux and Mac, on Windows (tested on Vista and 7), trying to delete nested, watched folders using Windows Explorer fails with a message akin to "Access Denied: You need permission to perform this action" when a file exists in one of the nested directories.

For example, if I watch a nested folder tree in Windows:

-- Folder A
   -- Folder A1
      -- File F

and try to delete Folder A, I get the said Access Denied error. However, it works fine if I:

  • Delete Folder A1 then delete Folder A
  • Delete File F then delete Folder A

Is there a way to use the nio2 WatchService to recursively watch a nested directory, but not act as though a program is accessing nested files?

like image 353
FR. Avatar asked Jun 06 '11 17:06

FR.


1 Answers

If you are watching a directory on Windows then the WatchService implementation has an open handle to that directory (that's the way that Windows works). That open handle doesn't prevent the directory from being deleted but it does prevent the directory's parent from being deleted immediately. As soon as you delete the watched directory then the handle is closed but it's possible that you will attempt to delete the directory before the handle is closed. When that happens you will get the access denied that you are seeing. I assume it works fine for you if you retry and this is because the handle will be closed by the time you retry.

The Sun JRE on Windows can use Windows' watch subtree capability if you specify the ExtendedWatchEventModifier.FILE_TREE modifier in the register call, which can help bypass this issue as it creates only one file handle.

like image 157
Alan Avatar answered Oct 02 '22 13:10

Alan