> But what memory size. The amount of space that
> directory uses or all the file inside the directory.
> And remember a directory is only a term, something
> used to help our tiny brains comprehend. The
> directory doesn't acutally contain all those files.
Sorry, I mean all the memory spaces used by all the files in a directory.
I have written a simple program. Is this feasible to retrieve what I want?
import java.io.*;
public class ShowFileSize
{
public static void main (String[]args)
{
File testFile = new File("***a path of a directory*****");
File [] testFiles = testFile.listFiles();
long fileSize = 0;
for (int i=0;i<testFiles.length;i++)
{
if (testFiles[i].isDirectory())
fileSize = getDirectorySize(testFiles[i].getPath());
else if (testFiles[i].isFile())
fileSize += testFiles[i].length()/1024;
}
System.out.println("Size of the directory: "+fileSize+"KB");
}
public static long getDirectorySize(String path)
{
long fileSize = 0;
File directory = new File(path);
File [] objInDirectory = directory.listFiles();
for (int i=0;i<objInDirectory.length;i++)
{
if (objInDirectory[i].isDirectory())
fileSize += getDirectorySize(objInDirectory[i].getPath());
else if (objInDirectory[i].isFile())
fileSize += objInDirectory[i].length()/1024;
}
return fileSize;
}
}
Message was edited by:
leolee1022
Message was edited by:
leolee1022>
> Is this feasible to retrieve what I want?
Of course the easiest solution would be to run your program and see what result you get. Two things:
Redundant code in your main method. Why not just call getDirectorySize with your root directory?
Your method is recursive and each recursion will have its own fileSize variable. Therefore the only value that will be returned will be the total size of all files in your root directory.
Modified version according to your advices:
import java.io.*;
public class ShowFileSize
{
private static long sizeOfDirectory = 0;
public static void main (String[]args)
{
getDirectorySize("****path of directory***");
System.out.println("Size of the directory: "+sizeOfDirectory+"KB");
}
public static long getDirectorySize(String path)
{
long fileSize = 0;
File directory = new File(path);
File [] objInDirectory = directory.listFiles();
for (int i=0;i<objInDirectory.length;i++)
{
if (objInDirectory[i].isDirectory())
sizeOfDirectory += getDirectorySize(objInDirectory[i].getPath());
else if (objInDirectory[i].isFile())
fileSize += objInDirectory[i].length()/1024;
}
return fileSize;
}
}
The result is much more close to the actual value. But why is there a difference?
My directory size is 187MB, but the result is 167MB.>