FilenameFilter

Introduction:

java.io.FileNameFilter is a interface which is for filtering by filename, if filename can meet the standard we set,return list of files.

usages:

creating a class and implementing the interface of FileNameFilter,what you gonna do is override the public function of accept.

  Details of accept function:

 boolean accept(File dir, String name);

Accept is a callback function,and first invoke is in the following functions.

(1)String []fs = f.list(FilenameFilter filter);

(2)File[]fs = f.listFiles(FilenameFilter filter);

  public String[] list(FilenameFilter filter) {
        String names[] = list();
        if ((names == null) || (filter == null)) {
            return names;
        }
        List<String> v = new ArrayList<>();
        for (int i = 0 ; i < names.length ; i++) {
            if (filter.accept(this, names[i])) {
                v.add(names[i]);
            }
        }
        return v.toArray(new String[v.size()]);
    }

 

 public File[] listFiles(FilenameFilter filter) {
        String ss[] = list();
        if (ss == null) return null;
        ArrayList<File> files = new ArrayList<>();
        for (String s : ss)
            if ((filter == null) || filter.accept(this, s))
                files.add(new File(s, this));
        return files.toArray(new File[files.size()]);
    }

 

Example:

public class Demo2 {

 public static void main(String[] args) {       

    File f = new File("C:/Users/caich5/Desktop/Chris/note"); 

    MyFilter filter = new MyFilter(".txt");    String[] files = f.list(filter);    

    for(String a:files){     

        System.out.println(a);   

     }   

}   

static class MyFilter implements FilenameFilter{   

     private String type;    

     public MyFilter(String type){     

          this.type = type;    

     }    

     public boolean accept(File f,String name){     

     return name.endsWith(type);    

      }  

   }

}

 

posted @ 2018-03-05 10:22  Chris,Cai  阅读(187)  评论(0编辑  收藏  举报