Wednesday, December 29, 2010

Getting size of File or Folder

Following code is used for getting size of the file or folder in bytes.

A class SizeCounter implements FileFilter interface from io package.

public class SizeCounter implements FileFilter {
private long total = 0;
public SizeCounter(){};
public boolean accept(File pathname) {
if ( pathname.isFile()) {
total+=pathname.length();
} else {
pathname.listFiles(this);
}
return false;
}
public long getTotal() {
return total;
}

private static long getFileOrDirectorySize(File file) {
SizeCounter counter = new SizeCounter();
file.listFiles(counter);
return counter.getTotal();
}

public static void main(String[] args) {
String folder = "E:\\test\\Shared";
long size = SizeCounter.getFileOrDirectorySize(new File(folder));
System.out.println("Size in Byte :" + size);
}
}

No comments:

Post a Comment