如何在 Java 中列出驱动器(HDD、USB、SD、CD/DVD)?

Tho*_*ile 0 java windows javafx

我正在尝试使用 Java 获取 Windows 上当前插入的存储驱动器的列表。

这是我在 StackOverflow 上的另一个问题中找到的代码片段:

File[] paths;
FileSystemView fsv = FileSystemView.getFileSystemView();

// returns pathnames for files and directory
paths = File.listRoots();

// for each pathname in pathname array
for(File path:paths)
{
    // prints file and directory paths
    System.out.println("Drive Name: "+path);
    System.out.println("Description: "+fsv.getSystemTypeDescription(path));
}
Run Code Online (Sandbox Code Playgroud)

问题实际上是我无法以某种方式使用 FileSystemView 并且我也无法导入它的库...可能是因为我正在使用 JavaFX?有没有可能解决这个问题?

先感谢您!

Jam*_*s_D 7

这没有经过测试,因为我无法访问 Windows 系统,但是不引入对 Swing 类的依赖的解决方案FileSystemView是使用java.nio.fileAPI。

您可以使用以下命令从文件系统获取所有根目录的列表:

FileSystem fs = FileSystems.getDefault();
for (Path root : fs.getRootDirectories()) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

您可以使用找到每个根目录的底层文件存储Files.getFileStore(...),然后查询文件存储以获取您需要的任何内容:

FileSystem fs = FileSystems.getDefault();
for (Path root : fs.getRootDirectories()) {
    FileStore store = Files.getFileStore(root);
    System.out.printf("Root: %s; File Store: %s; Total space: %d; Type: %s%n",
        root, store.name(), store.getTotalSpace(), store.type());
}
Run Code Online (Sandbox Code Playgroud)

如果您不介意额外的依赖项,请添加

requires java.desktop ;
Run Code Online (Sandbox Code Playgroud)

到你的module-info.java然后FileSystemView导入

import javax.swing.filechooser.FileSystemView ;
Run Code Online (Sandbox Code Playgroud)

  • @ThomasBasile 我看不到(除了轮询,例如使用“ScheduledService”等)。在 Mac 上,您可以使用“/Volumes”注册“WatchService”(当设备拔出时,它将更改内容),但据我所知,Windows 上没有等效的目录结构,并且“FileSystem”本身不是“Watchable”。 (3认同)