tags:

views:

105

answers:

3

One-Liner to list TXT-files.

import java.io.File;
import java.io.FilenameFilter;
...
files = dir.listFiles(new FilenameFilter() {
           public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
                }
           }
        );

Source.

Is there an one-liner to list dirs in a dir?

+3  A: 
import java.io.File;
import java.io.FileFilter;
...
files = dir.listFiles(new FileFilter() { 
       public boolean accept(File pathname) { 
            return pathname.isDirectory();
       } 
    });

Note the use of listFiles(FileFilter) rather than listFiles(FilenameFilter).

Michael Myers
+3  A: 
public static void main (String[] args)  throws Exception {
    File dir = new File("yourDir");

    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };

    File[] files  = dir.listFiles(fileFilter);

    for (File f : files)
        System.out.println( f.getName() );
}
Wajdy Essam
+3  A: 

This uses Commons IO, but really is the simplest way to list all the directory names. It also has a way more powerful set of filters that you can use for other purposes:

String[] dirNames = new File("/Users/jonathan").list(DirectoryFileFilter.INSTANCE);
for (String dirName: dirNames) 
    System.out.println("Directory Name: " + dirName);
Jon