There is a filenamefilter interface in Java that can filter out files or directories of the specified type, where the Accept (file file,string path) method must be overridden
public class Dirfilter implements filenamefilter{
Private String type;
Public Dirfilter (String tp) {
THIS.TYPE=TP;
}
Public Boolean accept (File fl,string path) throws exception{
File File=new file (path);
String Filename=file.getname ();
return Filename.indexof (type)!=-1;
}
}
Application method: If file is a directory, you can get all the names of files and directories in this directory by the list () method, the list () method, one is no parameters, one is to implement the parameters of the FilenameFilter interface, For example, to get all the Java files in a given directory, use the second list () method with parameters
public class test{
public static void Main (string[] args) {
try{
Specify the directory ("." Represents the current directory)
File Dir=new file (".");
String[] names;
Get all Java files
Dirfilter filter=new Dirfilter (". Java");
Names=dir.list (filter);
Print all Java file names
for (int i=0;i<names.length;i++) {
System.out.println ("I:" +i+ "Name:" +names[i]);
}
}catch (Exception e) {
E.printstacktrace ();
}
}
}
It is also possible to implement the Dirfilter class as an anonymous inner class for test, for example:
public class test{
Type: Must be declared as a final type, and as an anonymous inner class, the accessed variable must be declared as the final type
public static FilenameFilter filter (final String type) throws exception{
return new FilenameFilter () {
Public Boolean accept (File file,stirng path) {
String filename=new File (path). GetName ();
return Filename.indexof (type)!=-1;
}
};
}
public static void Main (string[] args) {
try{
File File=new file (".");
String names[];
Names=file.list (Filter (". Java");
for (int i=0;i<names.length;i++) {
System.out.println ("I:" +i+ "FileName:" +names[i]);
}
catch (Exception e) {
E.printstacktrace ();
}
}
}
Fundamentals 1: In a Java file, there is only one common class, that is, the class's modifier is public
Base 2: Any object defined in the interface has the default scope of public
The 3:exception namespace for basic knowledge is java.lang.Exception
Java file filter