Java nio WatchService: Watch Windows drives list

1.3k Views Asked by At

I want to get notified, when an USB-Drive is connected. So that java sais: "Drive H: created". Is there a way to do this with the WatchService? Watching the root-directory doesn't work. It just watches the root of the current drive: Paths.get("/").register

1

There are 1 best solutions below

2
On

You cannot do that with a WatchService. Since you are only worried about Windows, you can simply poll FileSystem.getRootDirectories and detect changes.

try {
   List<Path> roots = asList(FileSystems.getDefault().getRootDirectories());
   for(;;) {
        Thread.sleep(500);

        List<Path> newRoots = asList(FileSystems.getDefualt().getRootDirectories());
        for(Path newRoot : newRoots){
            if(!roots.contains(newRoot)) {
                System.out.println("New drive detected: " + newRoot);
            }
        }
        roots = newRoots;
    }
} catch(InterruptedException e) {
    e.printStackTrace();
    Thread.currentThread().interrupt();
}

If you wanted this to work on other operating systems, you would have to poll FileSystem.getFileStores and figure out a way to get the root path for a FileStore.

/e1

private <T> List<T> asList(Iterable<T> i) {
    if (i instanceof List) { return (List<T>) i; }

    List<T> l = new ArrayList<>();
    for (T t : i) {
        l.add(t);
    }
    return l;
}