The method listFiles of a directory returns the content of that directory. The method takes a filter in parameter that select the files or directory to return. A filter that only returns files is implemented.
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
};
File[] tab = file.listFiles( fileFilter );
The code of this example lists the directory in the directory v:/tmp. First the code call file.isDirectory() to validate that the Folder we are testing is a directory. It creates a FileFilter returning true only for if the Object is a File. The listFiles method is called with the filter; the file returned in the output are then written in System.out to confirm the filtering.
import java.io.File;
import java.io.FileFilter;
public class FolderListFiles {
public static void main(String[] argv) {
File file = new File("V:/tmp/");
if( file.isDirectory() ){
System.out.println( file.getName() + " is a directory " );
}
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
};
// List all the files using the filter
File[] tab = file.listFiles( fileFilter );
System.out.println( "The files in the directory are:" );
for( File current : tab ){
System.out.println( current.getAbsolutePath() );
}
}
}
tmp is a directory The files in the directory are: V:\tmp\00012-capture.jpg V:\tmp\01805-capture.jpg V:\tmp\01807-capture.jpg