问题
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.
回答1:
I have the same use case here and I am surprised that I did not find much useful online for such common scenario. I see some problems on the below approach. Let's say we utilize the walkTree method to scan the existing files in the directory and then register the directory for WatchService.
1. Files.walkTree(...);
2. Path dir = Paths.get(...);
3. WatchService watcher = dir.getFileSystem().newWatchService();
4. dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
5. // other logic
What about the files that are created after line 1 just finishes and before line 5 starts. I am just use this as a rough boundary to make discussions easier. The real boundary of window for opportunity to loss of files may be even broader.
回答2:
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.
回答3:
WatchService watches registered objects for certain types of changes and events. Code gets called when event, we are listening to, occurs. We may monitor either creation, deletion or modification of the file(s):
- ENTRY_CREATE
- ENTRY_DELETE
- ENTRY_MODIFY
If using
WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
… only newly created files will be reported. In order to observe already created files, use:
StandardWatchEventKinds.ENTRY_MODIFY
来源:https://stackoverflow.com/questions/9402908/java-7-watch-service