Lakshraj
Lakshraj

Reputation: 291

Total Size of Hard Disk using Java

I am trying to find the total size of Inbuilt hard disk. This code gives me just the size of C: drive.

long diskSize= new File("/").getTotalSpace();

I use this code but it also adding the size of drive on Network.

        long diskSize= 0;
        File[] drives = File.listRoots();
        if (drives != null && drives.length > 0) {
        for (File aDrive : drives) {
        diskSize=diskSize+(aDrive.getTotalSpace()/1000000000); //(1000000000)Converting to GB
        }
        }

Upvotes: 3

Views: 1444

Answers (1)

Mohamed Haneef
Mohamed Haneef

Reputation: 111

you can Use below code to get the total space of all directories

       package haneef.code.check;

       import java.io.File;

       import java.util.ArrayList;

       import java.util.List;

       public class DirSpace

       {

            static Double val=1000000000.00;

            public static void main(String[] args) 

            {
                 File file=new File("\\");
                 List<Double> values=new ArrayList<Double>();
                 File[] list=file.listRoots();
                 for(File driver:list)
                 {
                      Double driveGB=driver.getTotalSpace()/val;
                      System.out.println("Driver "+driver+" Space - "+driveGB);
                      values.add(driveGB);
                      Double cDrive=values.get(0);
                      for(int i=1;i<values.size();i++)
                      {
                            Double totalSpace=cDrive+values.get(i);
                            System.out.println("Final --- Total space is "+totalSpace);
                      }
                 }

             }

        }

Console output -

Driver C:\ Space - 107.583893504

Driver D:\ Space - 212.381724672

Final --- Total space is 319.965618176

Upvotes: 3

Related Questions