skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, October 31, 2012

Recursivey listing files and folders in java

Posted by Raju Gupta at 10:30 AM – 0 comments
 

This code snippet lists all the files and folders including the files in subdirectories present in the given path at any level recursively and displays in a tree structure

import java.io.File;

public class FileStructure {

  int tabCounter = 0;

  // obtain the list of files and folders in particular location
  public void listFilesAndFolders(String folder) {

    File file = new File(folder);

    if (!file.exists() || !file.isDirectory()) {

      System.out.println("Parameter is not a directory");
      System.exit(1);

    }

    File[] fileArray = file.listFiles();

    for (int i = 0; i < fileArray.length; i++) {

      if (fileArray[i].isDirectory()) {

        System.out.println(getTabs() + "- " + fileArray[i].getName());
        tabCounter++;
        listFilesAndFolders(fileArray[i].getAbsolutePath());

      }
      else {

        System.out.println(getTabs() + fileArray[i].getName());
      }
    }
    tabCounter--;

  }
  // provide a tab space to represent tree structure
  private String getTabs() {

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < tabCounter; i++)
      buffer.append("\t");

    return buffer.toString();
  }

  public static void main(String[] args) {

    FileStructure fileStructure = new FileStructure();
    fileStructure.listFilesAndFolders("C:\\temp");
  }
}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger