Java Reference
In-Depth Information
•
Owner
: The file's owner per the operating system.
Also, NIO.2 allows entering the specific attributes of the underlying operating sys-
tem. To do so, you first need to get a view that represents the operating system's file at-
tributes (in this example, it is a
DosFileAttributeView
). Once you get the view,
you can query and change the OS-specific attributes.
Note
The
AttributeView
will only work for the operating system that is inten-
ded (you cannot use the
DosFileAttributeView
in a *nix machine).
8-11. Monitoring a Directory for Changes
Problem
You need to keep track when a directory's content has changed (for example, a file was
added, changed, or deleted) and act upon those changes.
Solution
By using a W
atchService
, you can subscribe to be notified about events occurring
within a folder. In the following example, we subscribe for
ENTRY_CREATE,
ENTRY_MODIFY,
and
ENTRY_DELETE
events:
try {
System.out.println("Watch Event, press q<Enter> to
exit");
FileSystem fileSystem = FileSystems.getDefault();
WatchService service = fileSystem.newWatchService();
Path path = fileSystem.getPath(".");
System.out.println("Watching
:"+path.toAbsolutePath());
path.register(service,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);