Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...