learning java using WatchService monitoring file changes

import java.io.IOException;
import java.nio.file.*;

public class WatchServiceTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Paths.get("C:/").register(watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_CREATE);
        while ( true ){
            WatchKey key = watchService.take();
            for ( WatchEvent<?> event : key.pollEvents())
            {
                System.out.println(event.context() + "文件发生了 " + event.kind()  + "事件");
            }
            boolean  valid = key.reset();
            if (!valid)
                break;
        }
    }
}

output:

New Microsoft Word Document .docx files have ENTRY_CREATE event 
~ $ Microsoft Word .docx document files have ENTRY_CREATE event 
~ WRD0000.tmp file event occurred ENTRY_CREATE 
new Microsoft Word document .docx files have ENTRY_DELETE event 
~ WRL0001.tmp file occurred ENTRY_CREATE event 
~ WRD0000.tmp file event occurred ENTRY_DELETE 
new Microsoft Word document .docx files have ENTRY_CREATE event 
~ WRL0001.tmp files have ENTRY_DELETE event 
~ $ Microsoft Word .docx document files have ENTRY_DELETE event

  

Guess you like

Origin www.cnblogs.com/lianghong881018/p/11308021.html