How to Get Disk Space in Java

Getting file statistics (ie. disk space) can now be easily done in Java 1.6 using new methods that we recently released.   Let’s review the code below:

disk_spaceUsing the following methods, we will get the Total Disk Space and also find our how much space is Free.   We can then calculate space usage by subtracting the two.

  • getTotalSpace(): Returns the total capacity of the partition.
  • getFreeSpace():  Returns the free space available in the partition.

 

DiskSpaceUtil.java

package com.omega.tutorial;

import java.io.File;

public class DiskSpaceUtil {

  public static void main(String[] args) {

    File systemDrive = new File("C:");
    long totalDiskSpace = systemDrive.getTotalSpace();
    long freeDiskSpace = systemDrive.getFreeSpace();
    long usedDiskSpace = totalDiskSpace - freeDiskSpace;

    System.out.println("-----[ Disk space in Bytes ]-------");
    System.out.format("Total C: Disk Size : %,d bytesn", totalDiskSpace);
    System.out.format("Total Used Space   : %,d bytesn", usedDiskSpace);
    System.out.format("Total Free Space   : %,d bytesnn", freeDiskSpace);

    System.out.println("-----[ Disk space in MegaBytes ]-------");
    System.out.format("Total C: Disk Size : %,d MBn", totalDiskSpace/(1024*1024));
    System.out.format("Total Used Space   : %,d MBn", usedDiskSpace/(1024*1024));
    System.out.format("Total Free Space   : %,d MBnn", freeDiskSpace/(1024*1024));

    System.out.println("-----[ Disk space in GigaBytes ]-------");
    System.out.format("Total C: Disk Size : %,d GBn", totalDiskSpace/(1024*1024*1024));
    System.out.format("Total Used Space   : %,d GBn", usedDiskSpace/(1024*1024*1024));
    System.out.format("Total Free Space   : %,d GBnn", freeDiskSpace/(1024*1024*1024));
  }
}

Output:

disk_space_output

Other Related Posts

  • How to Get Disk Space in Java
    Getting file statistics (ie. disk space) can now be easily done in Java 1.6 using new methods that we recently released.
  • Creating Directory in Java
    Learn how to create directories using these easy to follow instructions.
  • Delete a directory in Java
    Learn how to delete a directory using these easy to follow instructions. In the java.io package you will need to use the File class and use the delete() method.

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *