Saturday Aug 31

Calculate file or folder disk space with Java

PDF Print E-mail
Thursday, 07 June 2012 14:47
AddThis Social Bookmark Button

Calculate compute file or folder disk space or usage using Java

Compute disk usage of a file or Folder

Compute disk usage of a file or folder using Java io.

Writing your own utility class

The following snippet give you a simple and effective way to calculate the disk space used by a file or folder using a FileFilter visitor .

    public class DiskUsage implements FileFilter
        public DiskUsage(){};        
        private long size = 0;        
        public boolean accept(File file)
            if ( file.isFile())
                size += file.length();
            return false;
        public long getSize()
            return size;

To compute and display the file size you have to give the file or folder as an instance to visit to your DiskUsage class then you can display the result using the getSize() method;

        File sampleFile = new File("sample.txt");
        DiskUsage diskUsage = new DiskUsage(); 
        System.out.println("Size of my file : "+ diskUsage.getSize());

Using Apache Commons IO

If you have apache commons io in your classpath you can use FileUtils.sizeOfDirectory(folder) for folder or sizeOf(file) for a file.

Tags: java , class , public , folder , visitor , file , long , calculate ,; ,;import , getsize() , filefilter , disk

Add comment

Security code

Java Tutorial on Facebook