How to list the file names in a directory in Java?

Lot of times we need to list or search a particular file in a directory in java. Java I/O API provides the methods to this operation.

We can use following methods to list the file names in a directory :

listFiles

This method returns the files in a directory with a format of abstract path names.
If the file calling this method is not a directory then this method returns null. We can also filter the files which returns using FileFilter and FileNameFilter passing as an argument to this method.

isDirectory

This particular method is important because it checks whether specified file is directory or not. This method returns true if the file with the path exists and it is a directory.

isFile

This method returns true if specified file is of type file.
Now we can use these methods to list the files or filenames in a directory.


import java.io.File;

public class ListFileDemo {

public static void main(String[] args) {

File directory = new File("C:/");
File[] filelist = directory.listFiles(); //Listing the files in directory

for ( int i = 0; i < filelist.length; i++) {
if ( filelist[i].isFile() ) { // Checking for file

System.out.println( "File " + filelist[i].getName() );

} else if ( filelist[i].isDirectory() ) { // Checking for directory

System.out.println( "Directory " + filelist[i].getName() );

}
}
}

}



For listing the files we can also set the FileFilters, if we want to retrieve only the directories then we can use following filter.


FileFilter dirFilter = new FileFilter() {
public boolean accept( File demoFile ) {
return demoFile.isDirectory(); // Accepts only directories.
}
};
files = dir.listFiles( dirFilter );



Similar to above filter mechanism, we can also use FilenameFilter which is used to have filter based on file names. Lets see the example below in which we are filtering the files only starting with character 'a'.


FilenameFilter fileFilter = new FilenameFilter() {
public boolean accept(File directory, String filename) {
return filename.startsWith("a");
}
};
files = directory.list( fileFilter ); // List the files starting with character 'a' .
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment