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).


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.

8 Years
Discussion Span
Last Post by DrApe1

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

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.