Difference between revisions of "List the files or subdirectories in a directory"

From CodeCodex

m (Java)
m (Java)
Line 7: Line 7:
 
</pre>
 
</pre>
 
===Java===
 
===Java===
This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see e33 Traversing the Files and Directories Under a Directory.
+
This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see [[Traversing the Files and Directories Under a Directory]].
 
<pre>
 
<pre>
 
     File dir = new File("directoryName");
 
     File dir = new File("directoryName");

Revision as of 03:23, 26 March 2007

Implementations

Common Lisp

(directory "*") ;lists all files and folders in current directory
(directory "/Users/Sathya/*") ;lists all files in specified folder
(directory "*.txt") ;lists all .txt files in current directory

Java

This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see Traversing the Files and Directories Under 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);