FileFilter and FilenameFilter can be implemented to filter files, they are interfaces, specific filtering rules need to be written by ourselves
1, FileFilter
1 PackageOrg.zln.io.file;2 3 ImportJava.io.File;4 ImportJava.io.FileFilter;5 6 /**7 * Extended Name filter only returns files with the specified extension8 * Created by Coolkid on 2015/6/21 0021.9 */Ten Public classExtensionfilterImplementsfilefilter{ One A //Extended Name - PrivateString extension; - the Publicextensionfilter (String extension) { - This. Extension =extension; - } - + @Override - Public BooleanAccept (file file) { + Booleanresult =false; A at if(File.isdirectory ()) {//Directory filter out -result =false; -}Else { -String fileName = File.getname ();//file name is not full path - intindex = Filename.lastindexof (".")); - if(Index = =-1){ inresult =false; -}Else if(Index = = Filename.length ()-1){ toresult =false; +}Else { - if( This. Extension.equalsignorecase (Filename.substring (index+1))){ theresult =true; * } $ }Panax Notoginseng } - returnresult; the } +}E:\GitHub\tools\JavaEEDevelop\Lesson1_JavaSe_Demo1\src\org\zln\io\file\ExtensionFilter.java
Test code
1 New File ("E:\\github\\tools"); 2 file[] files = file.listfiles (new extensionfilter ("Bat")); 3 for (File file1:files) {4 System.out.println (File1.getabsolutepath ()); 5 }
Only files with the extension "bat" will be filtered out, and files and folders of other extensions will not be listfiles.
At this point in the logic, we are based on the extension of the filter, of course, if necessary, we can also filter according to the other properties of the file
2, FilenameFilter
1 PackageOrg.zln.io.file;2 3 ImportJava.io.File;4 ImportJava.io.FilenameFilter;5 6 /**7 * Image Filter8 * Created by Coolkid on 2015/6/21 0021.9 */Ten Public classImageFilterImplementsFilenameFilter { One A Public Booleanisgif (String filename) { - if(Filename.tolowercase (). EndsWith (". gif")){ - return true; the}Else { - return false; - } - } + - Public Booleanisjpg (String filename) { + if(Filename.tolowercase (). EndsWith (". jpg")){ A return true; at}Else { - return false; - } - } - - Public Booleanispng (String filename) { in if(Filename.tolowercase (). EndsWith (". png")){ - return true; to}Else { + return false; - } the } * $ Panax Notoginseng @Override - Public BooleanAccept (File dir, String name) { theSystem.out.println ("DIR:" +Dir.getabsolutepath ()); + returnIsgif (name) | | Isjpg (name) | |ispng (name); A } the}E:\GitHub\tools\JavaEEDevelop\Lesson1_JavaSe_Demo1\src\org\zln\io\file\ImageFilter.java
Files are typically filtered using filenamefilter
FileFilter and FilenameFilter of Java IO