Watching for file and directory changes in Java

前端 未结 1 2007
栀梦
栀梦 2020-12-06 21:56

I\'m writing here mostly for advice on where to start. I\'ve already implemented a class that will recursively watch a directory using Java\'s WatchService. It works quite a

相关标签:
1条回答
  • 2020-12-06 22:49

    This will allow you to experiment with creating, deleting, moving and renaming files under D:\Temp, and should allow you to learn what you need:

    import static com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
    
    import java.nio.file.FileSystem;
    import java.nio.file.FileSystems;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.WatchEvent;
    import java.nio.file.WatchKey;
    import java.nio.file.WatchService;
    
    public class Foo3
    {
        public static void main(String[] args) throws Exception
        {
            FileSystem fs = FileSystems.getDefault();
            WatchService ws = fs.newWatchService();
            Path pTemp = Paths.get("D:/Temp");
            pTemp.register(ws, new WatchEvent.Kind[] {ENTRY_MODIFY, ENTRY_CREATE, ENTRY_DELETE}, FILE_TREE);
            while(true)
            {
                WatchKey k = ws.take();
                for (WatchEvent<?> e : k.pollEvents())
                {
                    Object c = e.context();
                    System.out.printf("%s %d %s\n", e.kind(), e.count(), c);
                }
                k.reset();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题