PDA

View Full Version : Traversing Folders


bbd
09-04-2008, 03:52 PM
Hey,

Basically I need to get a list of File pointers to ever file in a directory, including all subdirectories.

Currently I do this, but it only gets the files in that directory.

File directory = new File("c:\\MyDir");
File[] files = directory.listFiles();

I need everything in c:\MyDir\AnyOtherSubDir
Is there some already created easy code that I can use?

Thanks!

BBD

ess
09-04-2008, 04:41 PM
here is a simple example

import java.io.*;

public class RecursiveReader {
/*
* Constructor for RecursiveReader
*/
public RecursiveReader(){
// get handler to current directory
File currDir = new File(System.getProperty("user.dir"));

this.recursiveDirReader(currDir);
} //-- ends class constructor

private void recursiveDirReader(final File handler) {
if (handler.isDirectory()){
File [] files = handler.listFiles();
System.out.println("Now Reading: "+ handler.getAbsolutePath());
for(File f : files) {
if (f.isFile()){
// do something with the file.
System.out.println("File: '" + f.getName());
} //-- end if block
else if(f.isDirectory()){
// if directory...call the method for recursion
System.out.println("Now Reading: "+ f.getAbsolutePath());
recursiveDirReader(f);
} //-- ends else if block
} //-- ends foreach block
} //-- end if block
} //-- ends

public static void main(String[] args) {
new RecursiveReader();
} //-- ends class method main

} //-- ends class definition

Cheers
~E