Get free disk space In java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to get free disk space in Java. File.getTotalSpace(), File.getFreeSpace() and File.getUsableSpace() methods are used to get total size of the partition, unallocated bytes in the partition and bytes available to this virtual machine on the partition respectively.

File.getTotalSpace() - Returns the total size of the partition named by this abstract pathname.

File.getFreeSpace() - Returns the number of unallocated bytes in the partition named by this abstract path name.

File.getUsableSpace() - Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

Calculate Free Disk Space Example

package com.technicalkeeda.app;

import java.io.File;
import java.text.DecimalFormat;

public class DiskSpaceDetail {
    public static void main(String[] args) {
        File file = new File("C:");
        long totalSpace = file.getTotalSpace();
        long freeSpace = file.getFreeSpace();
        long usableSpace = file.getUsableSpace();

        System.out.println("Total Space:- " + displayFilesize(totalSpace));
        System.out.println("Total Usable Space:- " + displayFilesize(usableSpace));
        System.out.println("Total Free Space:- " + displayFilesize(freeSpace));
    }

    public static String displayFilesize(long fileSize) {
        if (fileSize <= 0) {
            return "0";
        } else {
            String[] fileUnit = new String[] {"B","KB","MB","GB","TB"};
            int group = (int)(Math.log10(fileSize) / Math.log10(1024));
            return new DecimalFormat("#,##0.#").format(fileSize / Math.pow(1024, group)) + " " + fileUnit[group];
        }
    }
}

Output

Total Space:- 234.9 GB
Total Usable Space:- 119.7 GB
Total Free Space:- 119.7 GB


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0696 seconds.