簡體   English   中英

使用java獲取文件夾的掛載點

[英]Get a folder's mount point using java

在 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));
    }

這些文件夾中的一些可能沒有指向已安裝的驅動器,而只是常規文件夾。 因此,我需要檢測這些文件是否是同一/ (根)分區上的常規文件夾,如果不是,則獲取它們的大小、可用空間、...

這是一種無需嘗試調用 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;
}

它假設一旦檢查已安裝文件系統級別以上的文件存儲,父目錄的文件存儲就會改變。 這適用於 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);

印刷:

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

然后要為每個文件系統掛載計算一次可用空間,您只需為從mountOf(p)返回的每個唯一路徑調用printDiskData(m.toFile()) mountOf(p)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM