我对上面提到的内容有点疑问。
供您参考,以下是此程序的代码:
import java.io.*;
import java.util.*;
public class DirectorySizeProcessor extends DirectoryProcessor
{
/*
Dan Czarnecki
October 17, 2013
Class variables:
private Vector<Long> directorySizeList
Variable of type Vector<Long> that holds the total file size of files in that directory
as well as files within folders of that directory
private Vector<File> currentFile
Variable of type Vector<File> that
Modification History
October 17, 2013
Original version of class
Implemented run() and processFile() methods
*/
private Vector<Long> directorySizeList;
private Vector<File> currentFile;
public DirectorySizeProcessor(File startingDirectory) throws FileNotFoundException
{
super(startingDirectory);
directorySizeList = new Vector<Long>();
currentFile = new Vector<File>();
}
/*
public void run()
{
File file;
file = directoryLister.next();
while(file != null) //the following will be called when the File object is not null
{
processFile(file);
file = directoryLister.next();
}
}
*/
public void processFile(File file)
{
Long hold;
Long currentSize;
Long finalTotal;
int index;
File parentFile;
parentFile = file.getParentFile();
index = this.currentFile.indexOf(parentFile);
if(index < 0)
{
this.directorySizeList.addElement((long)0);
this.currentFile.addElement(file.getParentFile());
}
while(index > 0)
{
currentSize = this.directorySizeList.get(index);
hold = file.length();
finalTotal = hold + currentSize;
//System.out.println("current size: " + parentFile);
//System.out.println("current size: " + currentSize);
System.out.println("file: " + file);
System.out.println("current size: " + file.length());
parentFile = parentFile.getParentFile();
index = this.getParentDirectory().indexOf(parentFile);
finalTotal = file.length() + finalTotal;
System.out.println("final total: " + finalTotal);
}
}
public void run()
{
File file;
file = directoryLister.next();
while(file != null) //the following will be called when the File object is not null
{
processFile(file);
file = directoryLister.next();
}
}
public Vector getParentDirectory()
{
return this.currentFile;
}
public Vector getDirectorySizeList()
{
return this.directorySizeList;
}
}
我知道问题主要在于我的processFile()方法。当我从我的Driver类运行它时(通过run()方法调用其中的processFile()方法),它正确显示每个文件的大小(以字节为单位),但我不认为它在计算整个目录的大小,因为它与属性窗口中显示的大小不匹配。有人可以帮助我吗?
答案 0 :(得分:0)
我认为您在向向量添加新目录/大小后忘记设置索引,这可能导致它总是跳过任何目录的第一个文件。
...
index = this.currentFile.indexOf(parentFile);
if(index < 0)
{
this.directorySizeList.addElement((long)0);
this.currentFile.addElement(file.getParentFile());
// set the index again to make it enter the while loop
index = this.currentFile.indexOf(parentFile);
}
while(index > 0)
{
...