java7新特性监听文件夹改变

  • Post author:
  • Post category:java


Java 7 uses the underlying file system functionalities to watch the file system for changes. Now, we can watch for events like creation, deletion, modification, and get involved with our own actions. For accomplish this task, we need:

• An object implementing the Watchable interface – the Path class is perfect for this job.

• A set of events that we are interested in – we will use StandardWatchEventKind which implements the WatchEvent.Kind<T>.

• An event modifier that qualifies how a Watchable is registered with a WatchService.

• A watcher who watch some watchable – per example, a watcher that watches the File System for changes. The abstract class is java.nio.file.WatchService but we will be using the FileSystem object to create a watcher for the File System.

The below example follows the above scenario:

import java.nio.file.Path;  
import java.nio.file.Paths;  
import java.nio.file.StandardWatchEventKind;  
import java.nio.file.WatchEvent;  
import java.nio.file.WatchKey;  
import java.nio.file.WatchService;  
import java.util.List;  
public class Main {  
    public static void main(String[] args) {  
        //define a folder root  
        Path myDir = Paths.get("D:/data");         
        try {  
           WatchService watcher = myDir.getFileSystem().newWatchService();  
           myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE,   
           StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);  
           WatchKey watckKey = watcher.take();  
           List<WatchEvent<?>> events = watckKey.pollEvents();  
           for (WatchEvent event : events) {  
                if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {  
                    System.out.println("Created: " + event.context().toString());  
                }  
                if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {  
                    System.out.println("Delete: " + event.context().toString());  
                }  
                if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {  
                    System.out.println("Modify: " + event.context().toString());  
                }  
            }  
             
        } catch (Exception e) {  
            System.out.println("Error: " + e.toString());  
        }  
    }  
} 

The FileSystem object and the WatchService can also be created like this:

  1. FileSystem fileSystem = FileSystems.getDefault();
  2. WatchService watcher = fileSystem.newWatchService();

And the Path (watchable), what we watch, and register it with the WatchService object like this:

  1. Path myDir = fileSystem.getPath(

    “D:/data”

    );
  2. myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE,
  3. StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);



版权声明:本文为li295214001原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。