Reputation: 27
i am working on an mobile application(using j2me), my requirement is to print all files in a directory including all its sub-directories without recursion,i already done it using recursion my code for recursion is here
public void pf1(String base_path1) throws IOException{
FileConnection fc1=(FileConnection) Connector.open(base_path1,Connector.READ_WRITE);
Enumeration filelist=fc1.list();
String filename;
while(filelist.hasMoreElements()){
filename=(String)filelist.nextElement();
fc1=(FileConnection)Connector.open(base_path1+filename,Connector.READ_WRITE);
if(!fc1.isDirectory()){
TotalFiles[TotalFileCount]=filename;
TotalFileCount++;
//System.out.println(filename);
}
else if(fc1.isDirectory()){
pf1(base_path1+filename);
}
}
System.out.println(TotalFileCount);
}
please help, if any. Thanks in advance
Upvotes: 0
Views: 748
Reputation: 44706
Make the stack explicit. I've done this in pseudo-code as this sounds a little home-worky! Your current structure is a little like this:
public void List(Directory directory) {
forevery file in directory
if (isDirectory(file)) List(file)
else print(file) // recursion uses a stack
}
Instead you can make the call-stack explicit using your own stack. The recursion becomes replaced with a while loop.
public void List(Directory directory) {
Stack directories = new Stack();
directories.push(directory);
while(!directories.Empty()) {
Directory dir = directories.pop();
forevery file in dir
if (IsDirectory(file)) directories.push(file)
else print(file);
}
}
Upvotes: 3