DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Java: Listing The Files Or Subdirectories In A Directory

05.15.2007
| 21312 views |
  • submit to reddit
        // Ref: Java Developers Almanac
// http://www.exampledepot.com/egs/java.io/GetFiles.html


    //
    // Example 1
    //

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

    //
    // Example 2
    //
    
    // 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);
    
    //
    // Example 3
    //

    
    // The list of files can also be retrieved as File objects
    File[] files = dir.listFiles();

    //
    // Example 4
    //
    
    // This filter only returns directories
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    files = dir.listFiles(fileFilter);