The filenamefilter interface in the Java Io stream is used to filter file names, that is, you can select files that meet certain conditions from the specified directory. This condition is set in the class that implements the filenamefilter interface. For specific implementation, see the following example:
Put several more files in the directory in the example and view the output result.
Test. Java
========================================================== ========================================================== ===
Package com. test;
Import java. Io .*;
Public class test {
Public static void main (string ARGs []) {
File dir = new file ("E:/WP/test/src/COM/test ");
String file [] = dir. List (New myfilter (". Java "));
For (INT I = file. length; I> 0; I --){
System. Out. println (file [I-1]);
}
}
}
Class myfilter implements filenamefilter {
String name;
Myfilter (string name ){
This. Name = Name;
}
Public Boolean accept (File Dir, string name ){
System. Out. println ("accept ()");
Return name. endswith (this. Name );
}
}
========================================================== ========================================================== ===
The filenamefilter interface defines only one method, public Boolean accept (File Dir, string name). According to the literal meaning, DIR is obviously the directory to be queried, name indicates the file name in Dir. The accept method specifies the conditions that the file name must meet. In the preceding example, the condition is a file with the extension of. java. The person who first came into contact with this interface may be surprised. He did not see the call to the accept method, but the result showed that the accept method was indeed called. Let's take a look at the source code of the List Method of the file class.
========================================================== ========================================================== ===
Public String [] list (filenamefilter filter ){
String Names [] = List ();
If (names = NULL) | (filter = NULL )){
Return names;
}
Arraylist v = new arraylist ();
For (INT I = 0; I <names. length; I ++ ){
If (filter. Accept (this, Names [I]) {
V. Add (Names [I]);
}
}
Return (string []) (V. toarray (New String [v. Size ()]);
}
========================================================== ========================================================== ===
The list method is overloaded in the file class. One has no parameters, and the other has only one filenamefilter parameter. This list method puts all the file names in the specified directory (the file object that calls the list method is a directory) into the names array, and then checks them cyclically. Returns a string [].