file.listRoots在Java中不能用于便携式USB驱动器。

huangapple go评论63阅读模式
英文:

file.listRoots not working for a portable USB drive in Java

问题

file.listRoots()对于内部文件驱动器信息运行良好,但无法获取USB和便携式文件信息。以下是我的代码:

    File[] paths; 
    try {
        // 返回文件和目录的路径名
        paths = File.listRoots();
        for (File path : paths) // 对于路径名数组中的每个路径名
            System.out.println(path); // 打印文件和目录路径
    } catch(Exception e) { // 如果出现任何错误
        e.printStackTrace();
    }

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

英文:

file.listRoots() works fine for internal file drive information, but is not getting USB and portable file info. Here is my code:

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

I don't understand why does my portable USB info not fetch?

答案1

得分: 2

如果您的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));
}
英文:

If your USB drive is connected and is accessible, you could check whether NIO code shows the volumes as follows:

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

Inside above loop you can also check other filesystem attributes such as removable storage flag:

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

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

huangapple
  • 本文由 发表于 2020年9月30日 14:04:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64131755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定