FileChangeObserver represents the state of files below a root directory,
checking the filesystem and notifying listeners of create, change or
delete events.
To use this implementation:
- Create
FileChangeListener implementation(s) that process
the file/directory create, change and delete events
- Register the listener(s) with a
FileChangeObserver for
the appropriate directory.
- Either register the observer(s) with a
FileChangeMonitor or
run manually.
Basic Usage
Create a
FileChangeObserver for the directory and register the listeners:
File directory = new File(new File("."), "src");
FileChangeObserver observer = new FileChangeObserver(directory);
observer.addListener(...);
observer.addListener(...);
To manually observe a directory, initialize the observer and invoked the
#checkAndNotify() method as required:
// intialize
observer.init();
...
// invoke as required
observer.checkAndNotify();
...
observer.checkAndNotify();
...
// finished
observer.finish();
Alternatively, register the oberver(s) with a
FileChangeMonitor,
which creates a new thread, invoking the observer at the specified interval:
long interval = ...
FileChangeMonitor monitor = new FileChangeMonitor(interval);
monitor.addObserver(observer);
monitor.start();
...
monitor.stop();
File Filters
This implementation can monitor portions of the file system
by using
FileFilters to observe only the files and/or directories
that are of interest. This makes it more efficient and reduces the
noise from
unwanted file system events.
Commons IO has a good range of
useful, ready made
File Filter
implementations for this purpose.
For example, to only observe 1) visible directories and 2) files with a ".java" suffix
in a root directory called "src" you could set up a
FileChangeObserver in the following
way:
// Create a FileFilter
Filter directories = Filters.and(
Filters.isDirectory(),
Filters.isVisible());
Filter files = Filters.and(
Filters.isFile(),
Filters.endsWith(".java"));
Filter filter = Filters.or(directories, files);
// Create the File system observer and register File Listeners
FileChangeObserver observer = new FileChangeObserver(new File("src"), filter);
observer.addListener(...);
observer.addListener(...);
FileEntry
FileInfo represents the state of a file or directory, capturing
File attributes at a point in time. Custom implementations of
FileInfo can be used to capture additional properties that the
basic implementation does not support. The
FileInfo#refresh(File)method is used to determine if a file or directory has changed since the last
check and stores the current state of the
File's properties.