Monday, 1 February 2016

How to calculate Free Disk Space in Java?

Calculate Free Disk Space using Apache Commons IO jar

Jar required: Apache Commons IO

Class used: org.apache.commons.io.FileSystemUtils.

Sometimes we need to check the free disk size before copying some data from one location to another.

package com.java.tricks;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;

public class CalDiskSpace {

      public static void main(String[] args) {
         try {

            // calculate free disk space in kilo-bytes - windows
            double freeDskSpace = FileSystemUtils.freeSpaceKb("C:");

            // FileSystemUtils.freeSpaceKb("/volume");  // unix

            double freeDskInGb = freeDskSpace / (1024 * 1024);
            System.out.println("Free Disk Space (Gb):" + freeDskInGb);

         } catch (IOException e) {
            e.printStackTrace();
         }
      }
}
Output:
Free Disk Space (Gb):359.8280334472656

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...