Java nio WatchService:观看Windows驱动器列表

当连接USB驱动器时,我想要得到通知。 所以,Java SAIS:“驱动器H:创build”。 有没有办法做到这一点WatchService? 看着根目录不起作用。 它只是观察当前驱动器的根:Paths.get(“/”)。register

你不能用WatchService来做到这WatchService 。 由于您只关心Windows,因此只需轮询FileSystem.getRootDirectories并检测更改即可。

 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(); } 

如果你想在其他操作系统上工作,你将不得不轮询FileSystem.getFileStores并找出获取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; }