Package filenameFilter; import java. io. file;/** implementation function: * obtain files in the specified format in the specified path; **/public class Test {public static void listPath (File file File) {// receive the filtered array of file objects // call listFiles (FilenameFilter filter) with the file object; method, // return the abstract path name array, these pathnames indicate the files and directories that meet the specified filter in the directory indicated by this abstract pathname [] = File. listFiles (new MyFilenameFilter (); // traverses the files that meet the conditions in the specified File path for (File f: files) {System. out. println (f);} * // traverses all the files in the specified File path that meet the filtering conditions for (File f: files) {if (f. isDirectory () {listPath (f);} else {System. out. println (f) ;}} public static void main (String [] args) {// create the File object file = new File ("F: \ test "); // call the method for filtering files and input and output the file objects, listPath (file );}}
Package filenameFilter; import java. io. file; import java. io. filenameFilter; // implements the FilenameFilter interface, this method can be used to filter file names. // This method is used to filter the public class MyFilenameFilter implements FilenameFilter {/*** @ param args ** of files ending in the specified format. The FilenameFilter interface is implemented, define the specified File filter **/@ Override // rewrite the accept method to test whether the specified File should be included in the public boolean accept (File dir, String name) of a File list) {// TODO Auto-generated method stub // create the return value boolean flag = true; // define the filtering condition // endWith (String str ); determine whether the if (name. toLowerCase (). endsWith (". jpg ") {} else if (name. toLowerCase (). endsWith (". txt ") {} else if (name. toLowerCase (). endsWith (". gif ") {} else {flag = false;} // return the defined return value // when true is returned, the input file meets the condition return flag ;}}