Listing the Files or Subdirectories in a Directory - Java File Path IO

Java examples for File Path IO:Directory Content

Description

Listing the Files or Subdirectories in a Directory

Demo Code

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;

public class Main {
  public static void main(String[] argv) {
    File dir = new File("directoryName");

    String[] children = dir.list();
    if (children == null) {
      // Either dir does not exist or is not a directory
    } else {/*from   www  . j a v  a 2s.  com*/
      for (int i = 0; i < children.length; i++) {
        // Get filename of file or directory
        String filename = children[i];
      }
    }

    FilenameFilter filter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return !name.startsWith(".");
      }
    };
    children = dir.list(filter);

    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);
  }
}

Related Tutorials