Java WatchService not generating events while watching mapped drives

后端 未结 5 1833
春和景丽
春和景丽 2020-11-30 05:58

I implemented a file watcher but I noticed that java nio file watcher doesn\'t generate events for files being copied on mapped drives. For instance, I\'ve run the file watc

5条回答
  •  北海茫月
    2020-11-30 06:28

    I had the same problem. I have solved it by creating a new thread in de main class and touching the files periodically so a new change event gets fired.

    The sample polls the dir for every 10 seconds does a touch.

    package com.ardevco.files;
    
    import java.io.IOException;
    import java.nio.file.DirectoryStream;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.attribute.FileTime;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Touch implements Runnable {
    
        private Path touchPath;
    
        public Touch(Path touchPath) {
            this.touchPath = touchPath;
            this.checkPath = checkPath;
    
        }
    
        public static void touch(Path file) throws IOException {
            long timestamp = System.currentTimeMillis();
            touch(file, timestamp);
        }
    
        public static void touch(Path file, long timestamp) throws IOException {
            if (Files.exists(file)) {
                FileTime ft = FileTime.fromMillis(timestamp);
                Files.setLastModifiedTime(file, ft);
            }
        }
    
        List listFiles(Path path) throws IOException {
            final List files = new ArrayList<>();
            try (DirectoryStream stream = Files.newDirectoryStream(path)) {
                for (Path entry : stream) {
                    if (Files.isDirectory(entry)) {
                        files.addAll(listFiles(entry));
                    }
                    files.add(entry);
                }
            }
            return files;
        }
    
        @Override
        public void run() {
            while (true) {
                try {
                    for (Path path : listFiles(touchPath)) {
                        touch(path);
                    }
                } catch (IOException e) {
                    System.out.println("Exception: " + e);
                }
    
                try {
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    System.out.println("Exception: " + e);
                }
            }
    
        }
    
    }
    

提交回复
热议问题