如何在java的FileWatcher中处理NoSuchFileException

如何在java的FileWatcher中处理NoSuchFileException,java,nio,file-watcher,Java,Nio,File Watcher,我正在监视一个目录的更改,其中一个文件夹正在抛出NoSuchFileException。我想跳过该文件夹并继续工作,如何处理此异常,而且该文件夹位于E:\ifkaar\sql setup 身体上 这是密码 public class FileWatcher { private final WatchService watcher; private final Map<WatchKey, Path> keys; static Logger log = Logger

我正在监视一个目录的更改,其中一个文件夹正在抛出NoSuchFileException。我想跳过该文件夹并继续工作,如何处理此异常,而且该文件夹位于
E:\ifkaar\sql setup
身体上

这是密码

public class FileWatcher {
    private final WatchService watcher;
    private final Map<WatchKey, Path> keys;
    static Logger log = LoggerFactory.getLogger(GitCloneRepo.class);

    /**
     * Creates a WatchService and registers the given directory
     */
    FileWatcher(Path dir) throws IOException {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<WatchKey, Path>();

        walkAndRegisterDirectories(dir);
    }

    /**
     * Register the given directory with the WatchService; This function will be called by FileVisitor
     */
    private void registerDirectory(Path dir) throws IOException
    {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        keys.put(key, dir);
    }

    /**
     * Register the given directory, and all its sub-directories, with the WatchService.
     */
    private void walkAndRegisterDirectories(final Path start) throws IOException {
        // register directory and sub-directories
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                registerDirectory(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                if (exc instanceof AccessDeniedException) {
                    return FileVisitResult.SKIP_SUBTREE;
                }

                return super.visitFileFailed(file, exc);
            }
        });
    }

    /**
     * Process all events for keys queued to the watcher
     */
    void processEvents() {
        for (;;) {

            // wait for key to be signalled
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                log.error("InterruptedException ",x);
                return;
            }

            Path dir = keys.get(key);
            if (dir == null) {
                log.warn("WatchKey not recognized!!");
                continue;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                @SuppressWarnings("rawtypes")
                WatchEvent.Kind kind = event.kind();

                // Context for directory entry event is the file name of entry
                @SuppressWarnings("unchecked")
                Path name = ((WatchEvent<Path>)event).context();
                Path child = dir.resolve(name);
                log.info("watching files");
                // print out event
                if (kind == ENTRY_MODIFY) {
                log.info("event.kind().name() {}: child {}", event.kind().name(), child);
                log.info("child {} ends with docx? {} ",child,child.endsWith(".docx"));
                String c= child.toString();
                log.info("**child {}***c.endsWith(.docx)"
                        + ""
                        + " {}",c,c.endsWith(".docx"));
                }
                // if directory is created, and watching recursively, then register it and its sub-directories
                if (kind == ENTRY_CREATE) {
                    try {
                        if (Files.isDirectory(child)) {
                            walkAndRegisterDirectories(child);
                        }
                    } catch (IOException x) {
                        // do something useful
                    }
                }
            }

            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid) {
                keys.remove(key);

                // all directories are inaccessible
                if (keys.isEmpty()) {
                    break;
                }
            }
        }
    }


 //working code
    public static void main(String[] args) throws IOException {
        try{
        Path dir = Paths.get("E:");
        FileWatcher fileWatcher=new FileWatcher(dir);
        fileWatcher.processEvents();
        }

        catch (AccessDeniedException xx) {
            log.error("AccessDeniedException  ",xx);
        }
         catch (FileSystemException x) {
            log.error("exception",x);
        }
        }

}
我只想让我的代码跳过
E:document\sql设置
这个目录并继续工作。我试图添加一个检查,但没有帮助

if (exc instanceof NoSuchFileException) {
                    return FileVisitResult.SKIP_SUBTREE;
                }

请引导

您可以使用
尝试…捕获
。我已经在上面粘贴的代码中完成了。您尝试了吗?它对我没有帮助
if (exc instanceof NoSuchFileException) {
                    return FileVisitResult.SKIP_SUBTREE;
                }