Hello guys,
I'm completely losing it. The question asks to emplement an electronic directory traverse in size a chosen folder (using JFileChooser)and print the structure with the calculated the size of each folder and file.
Finding the file size is easy using File.io getSize()
. However, to find the size of the folder I wrote the function below to do it.
My problem: My code is totally not calculating the inner folders' size, only the root
folder size is being calculated. I think I have a problem in my traverse method?
Traverse Class:
import java.io.File;
public class Traverser
{
private File fileObject;
public Folder originalFolder; //Selected Folder
public Folder childFolder; // Changes each round of recursion
public Traverser(File fileObject)
{
this.fileObject = fileObject;
this.originalFolder = new Folder(fileObject);
}
public void letsTraverse()
{
recursiveTraversal(this.fileObject, this.originalFolder);
}
private void recursiveTraversal(File fileObject, Folder parentFolder)
{
if (fileObject.isDirectory())
{
File files[] = fileObject.listFiles();
for (File afile : files)
{
if (afile.isDirectory()) {
this.childFolder = new Folder(afile);
parentFolder.add(childFolder);
}
recursiveTraversal(afile, this.childFolder);
}
} else if (fileObject.isFile()) {
this.originalFolder.add(new file(fileObject));
}
}
}
Folder Class:
import java.util.ArrayList;
import java.io.File;
public class Folder extends Documents
{
private ArrayList<Documents> filesStack;
public Folder(File folder)
{
this.filesStack = new ArrayList<Documents>();
this.name = folder.getName();
}
public void add(Documents doc)
{
this.filesStack.add(doc);
}
public long getSize()
{
for (Documents folder: filesStack)
{
this.size += folder.getSize(); // sum the size of childfiles
}
return this.size;
}
public void setName(String name)
{
this.name = name;
}
public String toString()
{
String result = name + "\t{Folder Size =" + readableFileSize(this.getSize()) + "}";
// I think I'm missing something, only the first folder
// size is being calculated
for (Documents elements: filesStack)
{
result += "\n " + elements.toString();
}
return result;
}
}
Output as Image (Sorry):
https://www.dropbox.com/s/peetbuuo51xdynq/2014-04-05%2003.52.57%20pm.png