Find the directory for a FileStore

前端 未结 4 1268
清歌不尽
清歌不尽 2020-12-16 00:21

I\'m trying to find a way to detect when a flash drive has been plugged into my computer. So far, the solution I found was to poll FileSystem#getFileStores for changes. This

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 01:08

    Here's a temporary work around until a better solution is found:

    public Path getRootPath(FileStore fs) throws IOException {
        Path media = Paths.get("/media");
        if (media.isAbsolute() && Files.exists(media)) { // Linux
            try (DirectoryStream stream = Files.newDirectoryStream(media)) {
                for (Path p : stream) {
                    if (Files.getFileStore(p).equals(fs)) {
                        return p;
                    }
                }
            }
        } else { // Windows
            IOException ex = null;
            for (Path p : FileSystems.getDefault().getRootDirectories()) {
                try {
                    if (Files.getFileStore(p).equals(fs)) {
                        return p;
                    }
                } catch (IOException e) {
                    ex = e;
                }
            }
            if (ex != null) {
                throw ex;
            }
        }
        return null;
    }
    

    As far as I know, this solution will only work for Windows and Linux systems.

    You have to catch the IOException in the Windows loop because if there is no CD in the CD drive an exception is thrown when you try to retrieve the FileStore for it. This might happen before you iterate over every root.

提交回复
热议问题