Original address: http://blog.sina.com.cn/s/blog_7a27a9bf0100s887.html
Sometimes you need to find a certain type of file in your program, such as the need to find all files that have a. java suffix name under the E:\data\file_selector_test directory. In fact, this function can also be implemented, very simple, only need to traverse the directory of all the files, to determine whether the end of the file name string is ". Java" can be. While this can be done, there is no need to do so, and there are already methods in the Java API to implement this functionality.
The file class has a listfiles (FilenameFilter filter). You can do this simply by implementing a simple filter. For example, I would like to find a file at the end of. Java or. txt under the E:\data\file_selector_test directory, which I can do. See the following example.
Class Name: Filenameselector
Import Java.io.File;
Import Java.io.FilenameFilter;
public class Filenameselector implements FilenameFilter
{
String extension = ".";
Public Filenameselector (String Fileextensionnodot)
{
Extension + = Fileextensionnodot;
}
@Override
Public Boolean Accept (File dir, String name)
{
return name.endswith (extension);
}
public static void Main (string[] args)
{
File directory = new file ("E:\\data\\file_selector_test");
List all Files
file[] files = directory.listfiles ();
System.out.println ("\ n Directory" +directory.getname () + "All Files under");
for (File file:files)
{
System.out.print ("" + File.getname ());
}
List all. txt files
file[] Txtfiles = directory.listfiles (new Filenameselector ("TXT"));
System.out.println ("\ n Directory" +directory.getname () + "TXT file");
for (File file:txtfiles)
{
System.out.print ("" + File.getname ());
}
List all. java files
file[] Javafiles = directory.listfiles (New Filenameselector ("Java"));
System.out.println ("\ n Directory" +directory.getname () + ". java files");
for (File file:javafiles)
{
System.out.print ("" + File.getname ());
}
}
}