Friday, April 15, 2011

Files-Directory listing in Java

This example lists the files and subdirectories in a directory.
File dir = new File("directoryName");
  String[] children = dir.list();
  if (children == null) {
      // Either dir does not exist or is not a directory
  } else {
      for (int i=0; i < children.length; i++) {
          // Get filename of file or directory
          String filename = children[i];
      }
  }
 
  // It is also possible to filter the list of returned files.
  // This example does not return any files that start with `.'.
  FilenameFilter filter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
          return !name.startsWith(".");
      }
  };
  children = dir.list(filter);
 
  // The list of files can also be retrieved as File objects
  File[] files = dir.listFiles();
 
  // This filter only returns directories
  FileFilter fileFilter = new FileFilter() {
      public boolean accept(File file) {
          return file.isDirectory();
      }
  };
  files = dir.listFiles(fileFilter);

Traversing the Files and Directories Under a Directory
This example implements methods that recursively visits all files and directories under a directory.
// Process all files and directories under dir
 public static void visitAllDirsAndFiles(File dir) {
     process(dir);
 
     if (dir.isDirectory()) {
         String[] children = dir.list();
         for (int i=0; i<children.length; i++) {
             visitAllDirsAndFiles(new File(dir, children[i]));
         }
     }
 }
 
 // Process only directories under dir
 public static void visitAllDirs(File dir) {
     if (dir.isDirectory()) {
         process(dir);
 
         String[] children = dir.list();
         for (int i=0; i<children.length; i++) {
             visitAllDirs(new File(dir, children[i]));
         }
     }
 }
 
 // Process only files under dir
 public static void visitAllFiles(File dir) {
     if (dir.isDirectory()) {
         String[] children = dir.list();
         for (int i=0; i<children.length; i++) {
             visitAllFiles(new File(dir, children[i]));
         }
     } else {
         process(dir);
     }
 }


No comments:

Post a Comment

Chitika