Get partition name from drive letter and vice versa

1.7k views Asked by At

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

There are 1 answers

0
StoopidDonut On

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.