Customizes a class that inherits the FilenameFilter class and obtains all files of the specified extension under a directory.
Method One:
/** * Description: * Custom Filterbyjava class, filter files with specified extension * */import Java.io.file;import Java.io.filenamefilter;public class Filterbyjava implements Filenamefilter{private string Ext;public Filterbyjava (string ext) {this.ext = ext;} Public Boolean Accept (File dir, String name) {//TODO auto-generated method Stubreturn Name.endswith (EXT);}}
Method Two:
FilenameFilter is an interface, so you need to write an implementation class to implement the interface. I want to implement the class of this interface and can filter multiple file types . The sample code is as follows:
Package Com.daxiang.filter;import Java.io.file;import Java.io.filenamefilter;import java.util.arraylist;import Java.util.iterator;import Java.util.list;public class Filefiltertool implements FilenameFilter {list<string> Types;protected Filefiltertool () {types = new arraylist<string> ();} Protected Filefiltertool (list<string> types) {super (); this.types = types;} Public Boolean Accept (File dir, String filename) {//TODO auto-generated method stubfor (iterator<string> Iterator = Types.iterator (); Iterator.hasnext ();) {String type = (string) iterator.next (); if (Filename.endswith (type)) {return true;}} return false;} /** * Add files of the specified type. * * @param type of file to be added, such as ". jpg". */public void AddType (String type) {Types.add (type);}}
in the code above, FilenameFilter object added a member variable types Span style= "COLOR: #555555" To receive the specified type. Method addtype (stringtype) is to add a file type that needs to be filtered for the filter. Its contents are the suffix name of the file, such as
Public Boolean Accept (File dir, String filename) is to achieve FilenameFilter interface to override the method, use the loop iteration to determine whether the file name suffix is Types The type in, is the return true . returns falsewhen there are no suffix names for the file in types .
In the defined class, the construction method writes two, one without parameters, at which point you create a ArrayList object that is used to store the file type. The other is the parameter with the List object, which is created by the user.
The following code is used:
Package Com.daxiang.filter;import Java.io.file;public class Test {public static void main (string args[]) {string path = "D: \\daxiang "; File File = new file (path); Filefiltertool filenamefilter = new Filefiltertool (); Filenamefilter.addtype (". jpg"); Filenamefilter.addtype (". mp3"); file[] files = file.listfiles (filenamefilter); for (int i = 0; i < files.length; i++) { System.out.println (Files[i].getname ());}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java File Class Learning Note 4: Customizing a class to filter files of the specified extension