FilenameFilter is used to filter the file names in the list, and today we start filenamefilter learning in Java.
The use of FilenameFilter in Java
Description of the Java documentation for FilenameFilter:
This Interface inch class File, and by the Abstract Window Toolkit'S File dialog component.
We have a case study to deepen our understanding and use of filenamefilter, the project structure is as follows:
First, define a class that implements FilenameFilter, which is used to filter the file name
PackageCom.huhx.file;ImportJava.io.File;ImportJava.io.FilenameFilter;ImportJava.util.regex.Pattern;/** * @authorHuhx*/ Public classDirfilterImplementsFilenameFilter {Privatepattern pattern; PublicDirfilter (String regex) {pattern=pattern.compile (regex); } @Override Public BooleanAccept (File dir, String name) {returnpattern.matcher (name). matches (); }}
Second, in the Dirlist.java class to test the use of
PackageCom.huhx.file;ImportJava.io.File;Importjava.util.Arrays;/** * @authorHuhx*/ Public classDirlist { Public Static voidMain (string[] args) {File FilePath=NewFile ("File"); String[] List= Filepath.list (NewDirfilter ("E.*\\.java")); Arrays.sort (list, string.case_insensitive_order); for(String dirname:list) {System.out.println (dirName); } }}
Third, the results are as follows:
EscapingDNs.javaExternal.java
Analysis of FilenameFilter
Let's take a look at the list (FilenameFilter filter) method of the file class with the following code:
Publicstring[] List (FilenameFilter filter) {String names[]=list (); if(Names = =NULL) || (Filter = =NULL)) { returnnames; } List<String> v =NewArraylist<>(); for(inti = 0; i < names.length; i++) { if(Filter.accept ( This, Names[i])) {V.add (names[i]); } } returnV.toarray (Newstring[v.size ()]);}
Call the list () method to get all the file names under the folder, and then traverse all the filenames. Filter by FilenameFilter 's Accept method, add the matching file name to the list, and finally return
Second, there is a similar method in file Listfiles (FileFilter filter) method, we look at the code:
Publicfile[] Listfiles (filenamefilter filter) {String ss[]=list (); if(ss = =NULL)return NULL; ArrayList<File> files =NewArraylist<>(); for(String s:ss)if(Filter = =NULL) || Filter.accept ( This, s)) Files.add (NewFile (S, This)); returnFiles.toarray (Newfile[files.size ()]);}
Similar to the list method above, except that the returned type is not the same.
The use of Java Foundation---->filenamefilter