javawindowsfilesystemsdiskspaceoshi

How to get disk usage stats of a share folder in windows in Java?


My shared folder looks like //shared/content and I want to know details like total space and available space of the folder. How can I do that in Java?

I have tried OSHI library but the file stores and disks that it provides does not have this shared folder. For linux it returns NFS file stores but I am not able to figure out how to locate the shared folder and get its space statistics.


Solution

  • You can retrieve information on the filesystem via the FileStore. This should work for your Windows shares using the UNC path, or the drive letter if you have mapped the UNC path:

    static void diskInfo(Path p) throws IOException {
        FileStore fs = Files.getFileStore(p);
        System.out.format("%s %d free of %d%n", p.toAbsolutePath(), fs.getUsableSpace(), fs.getTotalSpace());
    }
    

    Some examples on Windows, :

    diskInfo(Path.of("C:/"));
    diskInfo(Path.of("C:\\"));                // Same as previous line
    
    diskInfo(Path.of("//shared/content"));
    diskInfo(Path.of("\\\\shared\\content")); // Same as previous line
    

    Some examples on GNU/Linux:

    diskInfo(Path.of("/"));
    diskInfo(Path.of("/some/mount/point"));
    

    You can query same information via File:

    static void diskInfo(File f) {
        System.out.format("%s %d free of %d%n", f.getAbsolutePath(), f.getUsableSpace(), f.getTotalSpace());
    }