[JAVA] I want to monitor a specific file with WatchService

For example, if you want WatchService to detect that dir \ file.txt has changed, you'll want to write code like this, which raises a runtime exception (NotDirectoryException).

var file = Paths.get("dir", "file.txt");
var watcher = FileSystems.getDefault().newWatchService();
file.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

[JavaDoc for Path :: register](https://docs.oracle.com/javase/jp/8/docs/api/java/nio/file/Path.html#register-java.nio.file.WatchService As you can see in -java.nio.file.WatchEvent.Kind: A-java.nio.file.WatchEvent.Modifier ...-), the registration target of WatchService is a directory. Or it can be said that WatchService monitors the events that occur in the files and directories under the registered directory. Therefore, if you want to detect only the events of a specific file, you need to devise the following, for example.

var file = Paths.get("dir", "file.txt");
var directory = file.getParent();
var watcher = FileSystems.getDefault().newWatchService();
directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

//File until interrupted by interrupt etc..Keep monitoring txt.
while (true) {
    var watchKey = watcher.take();
    for (var event : watchKey.pollEvents()) {
        var modified = (Path) event.context();
        if (modified.equals(file.getFileName())) {
            // Do Something

You can get information about the entry where the event occurred with WatchEvent :: context. The return value of WatchEvent :: context is ʻObject, but in reality, a Pathobject is returned, so in the above example, it is cast as a variablemodified`.

Also, the Path object stored in modified is a relative path from the directory registered in WatchService. In short, it is var modified = Paths.get ("file.txt ");, so you need to be careful when comparing with ʻequals` etc.

Recommended Posts

I want to monitor a specific file with WatchService
I want to be able to read a file using refile with administrate [rails6]
I want to make a specific model of ActiveRecord ReadOnly
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to create a Parquet file even in Ruby
I want to develop a web application!
I want to recursively search for files under a specific directory
I want to make a button with a line break with link_to [Note]
I want to hook log file generation / open with log4j # FileAppender
I want to add a browsing function with ruby on rails
I want to use DBViewer with Eclipse 2018-12! !!
I want to write a unit test!
I want to extract between character strings with a regular expression
I made an app to scribble with PencilKit on a PDF file
I want to select multiple items with a custom layout in Dialog
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I want to display a PDF in Chinese (Korean) with thin reports
If you want to make a zip file with Ruby, it's rubyzip.
I want to ForEach an array with a Lambda expression in Java
Scraping and writing specific elements to a file
I want to test Action Cable with RSpec test
[Ruby] I want to do a method jump!
I want to use java8 forEach with index
I want to simply write a repeating string
I want to design a structured exception handling
I want to play with Firestore from Rails
I tried to break a block with java (1)
I want to perform aggregation processing with spring-batch
[Rails] I want to load CSS with webpacker
I want to create a Servlet war file with OpenJDK on CentOS7. Without mvn. With no internet connection.
I want to download a file on the Internet using Ruby and save it locally (with caution)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
Rails6 I want to make an array of values with a check box
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
I tried to implement file upload with Spring MVC
I want to use a little icon in Rails
I want to dark mode with the SWT app
I want to apply ContainerRelativeShape only to specific corners [SwiftUI]
I want to authenticate users to Rails with Devise + OmniAuth
I want to define a function in Rails Console
I tried OCR processing a PDF file with Java
I want to transition screens with kotlin and java!
I want to add a reference type column later
I want to click a GoogleMap pin in RSpec
I want to get along with Map [Java beginner]
I want to redirect sound from Ubuntu with xrdp
I want to connect to Heroku MySQL from a client
I want to create a generic annotation for a type
I want to add a delete function to the comment function
I want to read the property file with a file name other than application.yml or application- [profile name] .yml with Spring Boot.
I want to convert characters ...
How to request a CSV file as JSON with jMeter
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
[Java] I want to convert a byte array to a hexadecimal number
I want to find a relative path in a situation using Path
[Rails] I tried to create a mini app with FullCalendar
I want to push an app made with Rails 6 to GitHub