Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    bbd
    bbd is offline
    New to the CF scene
    Join Date
    Aug 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Traversing Folders

    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

  • #2
    ess
    ess is offline
    Regular Coder
    Join Date
    Oct 2006
    Location
    United Kingdom
    Posts
    865
    Thanks
    7
    Thanked 29 Times in 28 Posts
    here is a simple example

    PHP Code:
    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


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •