【问题标题】:file.listRoots not working for a portable USB drive in Javafile.listRoots 不适用于 Java 中的便携式 USB 驱动器
【发布时间】:2020-09-30 06:04:45
【问题描述】:

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 信息无法获取?

【问题讨论】:

  • 你得到什么输出,在什么操作系统上,这个问题与 javafx 有什么关系?
  • 我只得到像 C,D 这样的桌面驱动器没有得到 USB 信息,window10,我在 javafx 项目中使用这个代码
  • 这个纯 java 和 fx 无关 - 请删除 javafx 标签

标签: java usb-drive usb4java jmtp


【解决方案1】:

如果你的U盘已连接并且可以访问,你可以检查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));
}

【讨论】:

  • 我用过这个,但再次只显示 C、D、E 驱动器而不是我连接的 USB 设备
  • 您的驱动器是否在 Windows 资源管理器中分配或映射了驱动器号?如果没有,那么这段代码将无济于事。
  • 我的设备驱动器名称是 moto
  • 解决办法是什么?
  • 一些手机/平板电脑会暴露它们的磁盘,以便 Windows 驱动器映射工作 - 您将能够通过 Java 轻松读取/写入。但是,听起来您的设备可能使用媒体传输协议,并且您需要使用 MTP 感知客户端(Windows 资源管理器就是这样一个应用程序)。此处已提及此主题 [*.com/questions/39210514/…