Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Get Directory size in java

Tue Oct 21, 2008 7:52 pm

Can anybody help me to know the Directory size which contains
thousands of files. is there any method other than summing the size of
individual file inside the directory.



Re: Get Directory size in java

Tue Oct 21, 2008 7:53 pm

This class can compute the size of a directory, the key point is to use
recursion.

Code:
import java.io.File;


public class What033 {
public static void main(String[] args) {
What033 w = new What033();
File dir = new File("D:\\temp");
System.out.println(w.getDirSizeInMegabytes(dir));
}

long getDirSize(File dir) {
long size = 0;
if (dir.isFile()) {
size = dir.length();
} else {
File[] subFiles = dir.listFiles();

for (File file : subFiles) {
if (file.isFile()) {
size += file.length();
} else {
size += this.getDirSize(file);
}

}
}

return size;
}

long getDirSizeInMegabytes(File dir) {
return this.getDirSize(dir) / 1024 / 1024;
}
}


Re: Get Directory size in java

Tue Mar 17, 2009 7:13 pm

you can also use the apache commons io lib:

FileUtils.sizeOfDirectory

Code:
http://commons.apache.org/io/api-release/index.html


Re: Get Directory size in java

Thu Jun 07, 2012 4:31 pm

You can use use a FileFilter to visit the folder and compute the disk usage
Code:
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;
        }
    }


Code:
The complete tutorial is available at http://www.java-tutorial.ch/core-java-tutorial/calculate-file-disk-space/usage-with-java


Post a reply
  Related Posts  to : Get Directory size in java
 Set image size as a percentage of the page size     -  
 here how to increase java heap size     -  
 php Directory lister     -  
 phone directory     -  
 Creating a Directory in php     -  
 Delete directory in php     -  
 Upload File to a new directory     -  
 Listing the Contents of a Directory     -  
 Print all files in a directory     -  
 invalid drive or directory     -  

Topic Tags

Java Files and I/O