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
Asked
Active
Viewed 1,312 times
1 Answers
4
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;
}
-
What's the `asList` method? – Ky - Dec 28 '14 at 17:35
-
1I believe this was a modified snippet of code I wrote a while ago. `asList` converts an `Iterable` to a `List`, I'll edit it in. – Jeffrey Dec 28 '14 at 19:22