Total members 11893 |It is currently Tue Nov 05, 2024 7:45 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;
}
}


_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
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     -  
 Print all files in a directory     -  
 invalid drive or directory     -  
 Read the content from directory     -  
 Upload File to a new 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
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com