Listening for file system modifications
As of Java 1.7, the standard I/O API supports filing system notification events:
in other words, it provides a means for you to ask the
filing system to notify your program in the event of files being modified.
This functionality can be useful in situations such as:
- monitoring log files for important events such as user logins,
configuration changes, attempted breakins etc;
- receiving notifications from files that are edited/loaded by your program in order
to ensure that its copy in memory always matches the version on disk.
In Java, file notifications are provided via the Java WatchService API.
Some caveats to be aware of include the following:
- the granularity of watching is at the directory level: your application
watches directories for modifications and modifications of all files from those
directories will be notified to your application;
- notifications are sent in terms of three low-level categories: CREATION,
DELETION and MODIFICATION rather than high-level categories such as
"file renamed", "X characters added to file" etc—
notably, this means that your program will be notified when a file is modified "in some way", but will
not be told what aspect of the file (content/length, attributes, time stamp etc)
has actually been modified— if this is important, then you will need to
implement appropriate checks yourself upon being notified of a modification;
- what is logically a single modification may result in several modification events
being generated (e.g. one for the content, one for the time stamp):
your program should therefore handle this eventuality with appropriate
checks as necessary;
- your program will not be informed about which process modified the file in question;
- your program is notified about modifications "as they happen", but not given any clues as to
whether more modifications are expected (e.g. because a file has been opened/closed by
another process);
- the API is not necessarily well suited to a high volume of modifications on a particular
operating system: for example, it may be unsuitable for implementing an index or for
monitoring all changes to a filing system, but is rather designed for monitoring
a small number of specific directories on the system.
However, despite these restrictions, receiving filing system notifications via
the WatchService API can be immensely useful when used with care. In the following
sections we examine how to use
the WatchService API in detail.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.