Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 233
Skaros Ilias Avatar asked Jan 19 '26 12:01

Skaros Ilias


1 Answers

We use SIGAR extensively for cross-platform monitoring. This is the code we use to get the file system list:

/**
* @return a list of directory path names of file systems that are local or network - not removable media
*/
public static Set<String> getLocalOrNetworkFileSystemDirectoryNames() {
  Set<String> ret = new HashSet<String>();
  try {
    FileSystem[] fileSystemList = getSigarProxy().getFileSystemList();

    for (FileSystem fs : fileSystemList) {
      if ((fs.getType() == FileSystem.TYPE_LOCAL_DISK) || (fs.getType() == FileSystem.TYPE_NETWORK)) {
        ret.add(fs.getDirName());
      }
    }
  }
  catch (SigarException e) {
    // log or rethrow as appropriate
  }

  return ret;
}

You can then use that as the input to other SIGAR methods:

FileSystemUsage usageStats = getSigarProxy().getFileSystemUsage(fileSystemDirectoryPath);

The getSigarProxy() is just a convenience base method:

// The Humidor handles thread safety for a single instance of a Sigar object
static final private SigarProxy sigarProxy = Humidor.getInstance().getSigar();

static final protected SigarProxy getSigarProxy() {
  return sigarProxy;
}
like image 127
Martin Serrano Avatar answered Jan 21 '26 03:01

Martin Serrano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!