Home Articles How to Get Available Disk Space and List of Hard Drives in Java

How to Get Available Disk Space and List of Hard Drives in Java

Get a name, type, total space and free space of all drivers

by admin
How to get available disk space and list of hard drives in Java

To get information about hard drives in Java, you can use the FileStore class from the java.nio.file package. This class represents a file storage device, such as a hard drive or a removable drive, and provides methods for accessing information about the device, such as its name, type, and capacity.

Here is an example of how you can use the FileStore class to get information about hard drives:

import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class HardDriveInfo {
  public static void main(String[] args) throws Exception {
    // Iterate over the file stores
    for (FileStore store : FileSystems.getDefault().getFileStores()) {
      // Get the name and type of the file store
      String name = store.name();
      String type = store.type();
      
      // Get the total and available space on the file store
      long totalSpace = store.getTotalSpace();
      long availableSpace = store.getUsableSpace();
      
      // Print the information about the file store
      System.out.println("Name: " + name);
      System.out.println("Type: " + type);
      System.out.println("Total space: " + totalSpace + " bytes");
      System.out.println("Available space: " + availableSpace + " bytes");
    }
  }
}

This code iterates over the file stores available on the system, and for each file store it retrieves the name, type, total space, and available space.

Note that the FileStore class may not be available on all platforms, and some of the methods may throw an UnsupportedOperationException if they are not supported by the underlying file system.

This is an example of output:

java -cp /tmp/5wWxofGOmp HardDriveInfo
Name: overlay
Type: overlay
Total space: 16656896000 bytes
Available space: 6043144192 bytes
Name: proc
Type: proc
Total space: 0 bytes
Available space: 0 bytes
Name: tmpfs
Type: tmpfs
Total space: 67108864 bytes
Available space: 67108864 bytes
Name: /dev/sda1
Type: ext4
Total space: 16656896000 bytes
Available space: 6043140096 bytes
Name: shm
Type: tmpfs
Total space: 67108864 bytes
Available space: 66940928 bytes

This is just one way to get information about hard drives in Java. There are other ways you could achieve this, such as using the java.io.File class or calling native system functions using the Java Native Interface (JNI).

5/5 - (1 vote)

Related Posts

Leave a Comment