Get partition name from drive letter and vice versa

给你一囗甜甜゛ 提交于 2019-12-13 18:23:41

问题


The program I'm working on needs to access removable drives. Normally this wouldn't be a problem, because the mountpoint should stay the same (e.g.: On Ubuntu my phone's SD card gets mounted at /media/sebastian/GT-S5830/) But on Windows there are the drive letters, which can vary. (Same phone: Once E:\, after plugging in while camera was mounted at E:, it became F: and stayed.)

So I want to solve this by not saving the drive letter, but the partition name.

E.g.: When setting up, the path E:\DCIM\Camera\ was given. Now I want to do the following:

  • Get name of the partition mounted at E:
  • Save path to given directory as something like <partname>:\DCIM\Camera\
  • When accessing the device, resolve drive letter of partition named partname
  • Build path by concatenating drive letter and the path-part after the colon.

How can I get the partition name by giving the mountpoint on Windows and vice versa with Java?


回答1:


You might want to explore FileSystemView to get a lot more information about the file system. More assorted examples here.

For your cause you might want to get a handle on the removable disk and do something with the info:

FileSystemView fsv = FileSystemView.getFileSystemView();
        File[] files = File.listRoots();

        File[] roots = fsv.getRoots();
        for (int i = 0; i < roots.length; i++) {
            System.out.println("Root: " + roots[i]);
        }

        for (File fi : files) {
            if (fsv.getSystemTypeDescription(fi).contains("Local Disk")
                    || fsv.getSystemTypeDescription(fi).contains(
                            "Removable Disk")) {
                System.out.println(fsv.getSystemDisplayName(fi));
            }

        }

Output:

Root: C:\Users\popofibo\Desktop
Local Disk (C:)
Recovery (D:)
Removable Disk (E:)

You might want to check the Windows disks' volume information using JNA if need be - more details here.



来源:https://stackoverflow.com/questions/21064923/get-partition-name-from-drive-letter-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!