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

℡╲_俬逩灬. 提交于 2019-12-17 18:51:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6255463/java7-watchservice-access-denied-error-trying-to-delete-recursively-watched-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!