"Go" file class application-FilenameFilter and FileFilter

Source: Internet
Author: User

FilenameFilter & FileFilter

filenamefilter and filefilter are used to filter files, such as filtering, to. jpg or. Java end-Files by looking at their source code: by using the file class in the string[] list ( FilenameFilter Filter) or public file[] Listfiles (filefilter filter) method, Pass the FilenameFilter or FileFilter interface object as a parameter by implementing the Boolean accept(File dir, String name) or Boolean accept in the interface (File pathname) method to filter out the file that satisfies the condition. Difference:filenamefilter performance is better than filefilter .

Public file[] Listfiles (filefilter filter)

Returns an abstract path to the an array group, which represents the files and directories in the directory that this abstract path name represents for the specified filter. This method behaves the same as the Listfiles () method except that the path name in the returned array must satisfy the filter. If the given filter is NULL, all pathname names are accepted. Otherwise, the path name satisfies the filter if and only if the Filefilter.accept (Java.io.File) method that invokes the filter on the pathname returns TRUE.

/**

File class:

* Use string[] List (FilenameFilter filter) to traverse the specified directory under the specified suffix file.


How does the bottom layer implement filtering?

string[] List (filenamefilter filter)
principle: First, the directory below the file call list () method is all stored in a string[] array, and then iterate over the array,
Put the filter.accept (this, names[i]) condition into a ArrayList, and then put
list conversion to string[] array
The underlying source code parsing:
Public string[] List (FilenameFilter filter) {
String names[] = list ();//List all directory files
if ((names = = null) | | (filter = = null)) {//If there is no directory or file, returns null
return names;
        }
ArrayList v = new ArrayList ();
for (int i = 0; i < names.length; i++) {//Find file, Traverse
if (filter.accept (this, names[i])) {
V.add (names[i]);/put the satisfying conditions in the list collection
            }
        }
return (string[]) (V.toarray (New String[v.size () ));
    }

 *  filenamefilter interface
Span style= "color: #008000; font-size:12px; " > *  interface method:
 * Boolean The Accept (file dir,string name) can use this method to list files with certain suffixes under the specified directory.  
    dir-The directory where the files found are located.
    name-the name of the file.  
     Returns True if and only if the name should be included in the list of files, otherwise false.
 *
 */

Code:

1. Need to find files that end in. java under a path.

implementation: FilenameFilter Interface:

Package Com.lp.ecjtu.file.filter;import Java.io.file;import Java.io.filenamefilter;public class FileterByJava Implements FilenameFilter {        private String sufixname;  The name of the incoming filter is    Fileterbyjava (String sufixname) {this        . Sufixname = Sufixname;    }    @Override Public    Boolean Accept (File dir, String name) {        //system.out.println ("dir" +dir+ "___" + "name" + name); //Return dir:e:\workspace\iotest_____name:buf.txt    }}

Package Com.lp.ecjtu.file.filter;import Java.io.file;import Java.io.filenamefilter;public class FileListFilter {    public static void Main (string[] args) {Listfilefileterbyjava (); }/** * * Use the method to implement the FilenameFilter interface, * filter string[] List (filenamefilter filter) * File name filter */public static void Listfilefileterbyjava () {file F = new File ("E:" +file.separator+ "Workspace" +file.separator+ "IOTe         St "); string[] FileNames = f.list (newFileterbyjava (". Java"));//Use specific objects to put the filtered files in the. java file into the arraySystem.out.println (filenames.length);//contains the length of the. java file Arrayfor (String name:filenames) {//traverse the found. java FileSYSTEM.OUT.PRINTLN (name); }                 }/** * Lists the files with the suffix. Java in the specified directory, using the method string[] List (FilenameFilter filter) methods of using anonymous inner classes */public static void Listfilenamefileter () {file F = new File ("E:" +file.separator+ "Workspace" +file.separator+ "IO Test ");string[] Files= f.list (new FilenameFilter () {//Use Anonymous inner class method @Override public Boolean Accept (File dir, String name) { //TODO auto-generated Method Stub//system.out.println ("Dir:" +dir+ "name ..." +name); /Test Description DIR Indicates the specified directory, name represents the specified directory names return Name.endswith (". Java"); //The display of files and folders under the specified directory is controlled by the return value of the anonymous inner class, showing only. java Files  } });System.out.println (files.length);//Traverse files and directories below the specified directoryfor (String file:files) {System.out.println (file); }    }}

/* FileFilter interface
* interface method:
* Boolean Accept (file dir) can use this method to list files with certain suffixes under the specified directory.
Parameters:
Dir-the directory where the files found are located.
Return:
Returns true if and only if the name should be included in the file list, otherwise false.
*/

Code:

Requirements: Now requires a directory to enter a file, and then delete all the backup files inside, the backup files are ". bak" or ". Bak "ends, which means the filter file type is either. bak or. bak files after deletion.

The first method, using the method of the FileFilter inner class, operates:

Code:

Package Com.lp.ecjtu.file.filter;import Java.io.file;import Java.io.filefilter;public class FileFilterDemo {public St        atic void Main (string[] args) {file Dir = new File ("e:\\ copy Demodir");    Listfilefileter (dir); }/** * Now requires the entry of a directory of files, after which all the backup files are deleted, the backup files are ". bak" or ". Bak "End, filter file type to. bak file * /public static void Listfilefileter (File dir) {if (dir.exists ()) {//Anonymous inner class that takes the FileFilter interface object as a parameterfile[] files = dir.listfiles (new FileFilter () {@Override public boolean accept (File Pathnam                    e) {if (Pathname.isdirectory ()) {return true; } String name = Pathname.getname ();//Get the name of the file e:\ copy Demodir\learn\sgim_piccell.v1.bin.bakSystem.out.println ("****************" +pathname); Return Name.endswith (". Bak") | | Name.endswith (". BAK ");//filter file types are. bak or. bak files, and do not contain. bak or. bak files}            });//Depth traversal file, recursivefor (int i=0;i<files.length;i++) {if (Files[i].isfile ()) {//If you traverse to a file, delete it directlyFiles[i].delete (); }else{//or directory, continue traversal until it is file, then deleteListfilefileter (Files[i]); }}}else{throw new RuntimeException ("Action file or directory does not exist!        "); }    }}

The second method implements the interface, using the object of the real class:

 package Com.lp.ecjtu.file.filter;import Java.io.file;import Java.io.filefilter;import Java.io.FilenameFilter; /** * Requirements: Enter a file directory, then delete all of the backup files, the backup files are ". Bak" and ". BAK "End * */ public class Fileterbyfile implements FileFilter {@Override public boolean accept (File pathname)        {if (Pathname.isdirectory ()) {return true;        } String name = Pathname.getname ();        //TODO auto-generated Method stub         System.out.println ("****************" +pathname); Return Name.endswith (". Bak") | | Name.endswith (".    BAK "); }    }
Package Com.lp.ecjtu.file.filter;import Java.io.file;import Java.io.filefilter;public class FileFilterDemo {        public static void Main (string[] args) {file Dir = new File ("e:\\ copy Demodir");    Listfilefileterbak (dir); }    /**
* Delete files that meet the criteria
* @param dir
* /public static void Listfilefileterbak (File dir) {if (dir.exists ()) {file[] files = Dir.listfiles (New Fileterbyfile ()); //Use filter for (File file:files) {if (File.isdirectory ()) {Listfilefileter Bak (file); }else{File.delete (); }}}else{throw new RuntimeException ("Action file or directory does not exist! "); } }}

"Go" file class application-FilenameFilter and FileFilter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.