file.listRoot在Java中无法用于便携式USB驱动器

问题描述

file.listRoots()适用于内部文件驱动器信息,但不能获取USB和便携式文件信息。这是我的代码

File[] paths; 
try {
    // returns pathnames for files and directory
    paths = File.listRoots();
    for (File path : paths) // for each pathname in pathname array
        System.out.println(path); // prints file and directory paths
} catch(Exception e) { // if any error occurs
    e.printstacktrace();
}

我不明白为什么我的便携式USB信息无法获取

解决方法

如果USB驱动器已连接并且可以访问,则可以检查NIO代码是否如下所示显示卷:

for (Path root : FileSystems.getDefault().getRootDirectories()) {
    FileStore fs = Files.getFileStore(root);
    System.out.format("FileStore %s\tName: '%s'\tType: %s%n",root,fs.name(),fs.type());
    System.out.println();
}

在上述循环中,您还可以检查其他文件系统属性,例如可移动存储标志:

String[] attrs = new String[]{"volume:isRemovable"};

for (String s : attrs) {
    System.out.format("\t%s=%s",s,fs.getAttribute(s));
}