tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > System Space

System Space 

This following example shows how to access disk space information from File API.

File Name  :  
com/bethecoder/tutorials/system/SystemSpace.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.system;

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

public class SystemSpace {
  
  public static void main(String[] args) {
    
    File [] sysRoots = File.listRoots();

    for (int i = 0; i < sysRoots.length; i++) {            
      System.out.println(sysRoots[i" drive free space : " 
          bytes2String(sysRoots[i].getFreeSpace()));
      System.out.println(sysRoots[i" drive usable space : " 
          bytes2String(sysRoots[i].getUsableSpace()));
      System.out.println(sysRoots[i" drive total space : " 
          bytes2String(sysRoots[i].getTotalSpace()));
      System.out.println();
    }
  }
  
  public static final long SPACE_KB = 1024;
  public static final long SPACE_MB = 1024 * SPACE_KB;
  public static final long SPACE_GB = 1024 * SPACE_MB;

  public static String bytes2String(double dataSize) {
    
    NumberFormat nf = new DecimalFormat();
    nf.setMaximumFractionDigits(2);
    
    try {
      if dataSize < SPACE_KB ) {
        return nf.format(dataSize" Bytes";
      else if dataSize < SPACE_MB ) {
        return nf.format(dataSize/SPACE_KB" KB";
      else if dataSize < SPACE_GB ) {
        return nf.format(dataSize/SPACE_MB" MB";
      else {
        return nf.format(dataSize/SPACE_GB" GB";
      }          
    catch (Exception e) {
      return dataSize + " Bytes";
    }

  }/* end of bytes2String method */
}
   

It gives the following output,
A:\ drive free space : 0 Bytes
A:\ drive usable space : 0 Bytes
A:\ drive total space : 0 Bytes

C:\ drive free space : 1.06 GB
C:\ drive usable space : 1.06 GB
C:\ drive total space : 9.32 GB

D:\ drive free space : 764.45 MB
D:\ drive usable space : 764.45 MB
D:\ drive total space : 18.62 GB

E:\ drive free space : 938.19 MB
E:\ drive usable space : 938.19 MB
E:\ drive total space : 18.62 GB



 
  


  
bl  br