I'm a little new to programming and for my class I've been asked to do a recursive program where you input a directory and it will find all the files in that directory and any subdirectories in that directory, etc etc until there aren't any more subdirectories.

Quite honestly, I'm stumped. Recursion is really confusing for me and I could use a little help. Any coding/implementation help would be wonderful if you know how to do this. I would also accept any help regarding the stop condition of the recursion, how to enter a directory once you've found out that it's a directory via isDirectory() or if there is some other methods of retreiving the files in a directory and checking if there is another directory inside that, and/or generally anything i should know about this recursive program that could be helpful.

If you do provide code, please note that I need to put it in a JTextArea from the Swing library eventually (if that helps).

Thanks

p.s. I've searched for something like this but either it doesn't use the File library as i'm supposed to or it's not really similar to my problem.

Recommended Answers

All 2 Replies

A Recursion is a mecanisme that allow a function to call it self:
By exemple:
let's suppose that we have a void function that is public and that takes no formal parameters for simplicity.

public void [B]recursiveFunction[/B](){
//do some staff  here
[B]recursiveFunction[/B]();
}

This is usuful typically when traversing tree strunctures. Even in the most algothithms it is recomanded to a void the recursivity.
Now what about file directory listing?
All you need is the packages: "java.io.*" and one function (named "listfiles" for instance)that take a string as parameter (name directory let's see that isname is "directory") and that implements this algorithm:

create a file (suppose it's name is "f") of type File by passing the formal parameter ("directory") to it:

call the isDirectory function on "f" and test if it is true ;
if not throw an exception
if it is true call listFiles function on "f" and save the return value in an array of files (let its name be "fs";

Loop loope over fs and make this test:
if not isDirectory fs then it is a file
//do what ever you want with your file

else //the it is a Directory
recall your recursive function with the new parameter fs.toString


Hope it helps.

bump in hopes of more help/information. Not that the above poster wasn't helpful at all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.