javasigar

Get a list of disks to read free space in Java, using Sigar


I need to get the free available disk space for all disks in system, or all partitions, I don't mind that. (I dont have to use Sigar, but I am using it already on the project for some other processes, so I can use it for this as well) I am using Sigar API and got this

public double getFreeHdd() throws SigarException{
        FileSystemUsage f= sigar.getFileSystemUsage("/");
        return ( f.getAvail()); 
    }

But this only gives me the system partition (root), how can i get a list of all partition and loop them to get their free space? I tried this

FileSystemView fsv = FileSystemView.getFileSystemView();
        File[] roots = fsv.getRoots();
        for (int i = 0; i < roots.length; i++) {
            System.out.println("Root: " + roots[i]);
        }

But it only returns the root dir

Root: /

Thanks

Edit it seems that I could use FileSystem[] fslist = sigar.getFileSystemList();
But the results i am getting do not match the ones i get from the terminal. On the other hand on this system I am working on, i have 3 disks with a total 12 partitions, so i might be loosing something there. Will try it on some other system in case i can make something useful out of the results.


Solution

  • You can use java.nio.file.FileSystems to get a list of java.nio.file.FileStorages and then see the usable/available space. Per instance (assuming that you are using Java 7+):

    import java.io.IOException;
    import java.nio.file.FileStore;
    import java.nio.file.FileSystem;
    import java.nio.file.FileSystems;
    import java.util.function.Consumer;
    
    public static void main(String[] args) {
        FileSystem fs = FileSystems.getDefault();
        fs.getFileStores().forEach(new Consumer<FileStore>() {
            @Override
            public void accept(FileStore store) {
                try {
                    System.out.println(store.getTotalSpace());
                    System.out.println(store.getUsableSpace());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    Also, keep in mind that FileStore.getUsableSpace() returns the size in bytes. See the docs for more information.