Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA 7 watch service

How can I have the watch service process any files that are in the directory on when the application starts up?

I already have the application running, but I noticed that only new files that are dropped in the directory are processed but files that were there from the start are ignored.

like image 571
Micheal Noel Avatar asked Dec 04 '25 02:12

Micheal Noel


1 Answers

The WatchService does only cope with changes in the filesystem. The files that are already there have not been changed and thus aren't picked up by the WatchService. You would have to traverse all files and directory recursivly to get an initial 'view' of the files:

Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {
                // do something with the file
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir,
                    BasicFileAttributes attrs) throws IOException {
                // do something with the directory
                return FileVisitResult.CONTINUE;
            }
        });

All changes, that occur after initializations are then picked up by the WatchService.

like image 152
Clemens Sum Avatar answered Dec 05 '25 16:12

Clemens Sum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!