简体   繁体   中英

Get a folder's mount point using java

On an Ubuntu system, I'm searching inside /media directory and assume each folder is a mounted filesystem to get its size and information:

String username = System.getProperty("user.name");
File media = new File("/media/" + username);
System.out.println("Partition: " + media.getAbsolutePath());

File[] fileList = media.listFiles();

if (fileList != null)
    for (File f : fileList) {
        if (f.isDirectory())
            printDiskData(f);
        }


void printDiskData(File partitionMountPoint) {
        System.out.println(partitionMountPoint.getAbsolutePath());
        System.out.println(String.format("Total disk size: %.2f GB", partitionMountPoint.getTotalSpace() / 1073741824f));
        System.out.println(String.format("Free disk size: %.2f GB", partitionMountPoint.getFreeSpace() / 1073741824f));
        System.out.println(String.format("Usabale disk size: %.2f GB", partitionMountPoint.getUsableSpace() / 1073741824f));
    }

There's a possibility some of these folders don't point to a mounted drive, and are just regular folders. So I need to detect whether these files are regular folders on the same / (root) partition or not, if not, then get their size, free space,...

This is a way to determine the top level mount point of a directory path in Java without trying calls to Linux files or scripts.

public static Path mountOf(Path p) throws IOException {
    FileStore fs = Files.getFileStore(p);
    Path temp = p.toAbsolutePath();
    Path mountp = temp;

    while( (temp = temp.getParent()) != null && fs.equals(Files.getFileStore(temp)) ) {
        mountp = temp;
    }
    return mountp;
}

It makes the assumption that the filestore of a parent directory will change once checking the filestore above the level of the mounted filesystem. This works on Windows 10 and WSL Ubuntu JDK15 - not sure about other versions.

Path p = Path.of("/mnt/c/dev/tools");
Path m = mountOf(p);
System.out.println("Mount point of "+p+" => "+m);

Prints:

Mount point of /mnt/c/dev/tools => /mnt/c

Then to work out free space once per filesystem mount you'll only need to call printDiskData(m.toFile()) for each unique path returned from mountOf(p) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM