Total members 11678 |It is currently Sat Nov 25, 2017 5:35 am Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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.




Author:
Proficient
User avatar Posts: 280
Have thanks: 1 time

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;
}
}



Author:
Mastermind
User avatar Posts: 2707
Have thanks: 74 time

you can also use the apache commons io lib:

FileUtils.sizeOfDirectory

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



Author:
Newbie
User avatar Posts: 1
Have thanks: 0 time

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



Author:
Post new topic Reply to topic  [ 4 posts ] 

  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







Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team