Saturday Aug 31

Key Concepts

Calculate file or folder disk space with Java

PDFPrintE-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.

import java.io.File;
import java.io.FileFilter;
    public class DiskUsage implements FileFilter
    {
        public DiskUsage(){};        
        private long size = 0;        
        public boolean accept(File file)
        {
            if ( file.isFile())
                size += file.length();
            else
                file.listFiles(this);
            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(); 
        diskUsage.accept(file);
        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, java.io.filefilter;, java.io.file;import, getsize(), filefilter, disk

Add comment


Security code
Refresh

Java Tutorial on Facebook