简体   繁体   English

使用java获取文件夹的挂载点

[英]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:在 Ubuntu 系统上,我在/media目录中搜索并假设每个文件夹都是一个已安装的文件系统以获取其大小和信息:

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.这是一种无需尝试调用 Linux 文件或脚本即可确定 Java 中目录路径的顶级挂载点的方法。

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.这适用于 Windows 10 和 WSL Ubuntu JDK15 - 不确定其他版本。

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) .然后要为每个文件系统挂载计算一次可用空间,您只需为从mountOf(p)返回的每个唯一路径调用printDiskData(m.toFile()) mountOf(p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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