
("Watch Service registered for dir: " + dir.getFileName()) įor (WatchEvent event : key. Path dir = Paths.get("E:/Test/Download") ĭir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY) WatchService watcher = FileSystems.getDefault().newWatchService()
Filewatcher java how to#
* This program demonstrates how to use the Watch Service API to monitor change
Filewatcher java code#
If the reset() method returns false, the directory is inaccessible (might be deleted), so the loop exits.The following is complete code of a demo program that watches a directory for all changes, and pays attention to the modification of a file named DirectoryWatchDemo.java: package If not, the key won’t receive further events. For example: while (true) NOTES: It’s very important that the key must be reset after the events have been processed. For an in-depth guide to testing with JUnit, check out our excellent Guide to JUnit 5. In this quick tutorial, we’ll take a look at how we can accomplish this using the TestWatcher API provided by JUnit. We’ll get a if trying to do so.Next, write an infinite loop to repeatedly poll the events fired by the watcher and process the events accordingly. Overview When unit testing, we may, periodically, wish to process the results of our test method executions.

NOTES: The Watch Service API does not allow registering an individual file. This event is always implicitly registered so we don’t need to explicitly specify it in the register() method.Īll these event types are declared in the class. OVERFLOW: indicates that the event might have been lost or discarded.ENTRY_MODIFY: indicates that a directory or file is modified.

ENTRY_DELETE: indicates that a directory or file is deleted.ENTRY_CREATE: indicates that a directory or file is created. Defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.All interfaces and classes in the Watch Service API can be found in the package, create a new WatchService object like this: WatchService watcher = FileSystems.getDefault().newWatchService() Then register this WatchService for a given directory like the following: Path dir = Paths.get("Path/To/Watched/Directory") ĭir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY) The register() method of the Path class takes a WatchService object and a varargs list of event types which the application needs to get notified. In this article, we’ll see how to use this API in the simplest form with a simple demo program. The Watch Service API is fairly simple to use, and relieves programmers from using third party libraries for files change monitoring. Java 7 adds a new feature for its NIO package called Watch Service API which allows applications monitoring directories and files for change events such as creation, deletion and modification.
