listFiles(),如何实现FileFilter及其FilenameFilter接口,list()的使用

  1. import java.io.*;
    //Oniy类实现了FileFilter接口
    class OnlyExt implements FilenameFilter{
    	String ext;
    	public OnlyExt(String ext){
    		this.ext="."+ext;
    	}
    	public boolean accept(File dir,String name){
    		return name.endsWith(ext);
    	}
    }
    class FileFilterTest implements FileFilter{
    	String filename;
    	FileFilterTest(String filename){
    		this.filename=filename;
    	}
    	public boolean accept(File name){
    		if(name.getName().lastIndexOf(filename)!=-1)
    			return true;
    		else return false;
    	}
    	
    }
     class DirListOnly {
    	  static void p(File[] f){
    		 for(File x:f)
    			 System.out.println(x);
    		 System.out.println();
    	 }
    public static void main(String[] args){
    	String dirname="c:/";
    	File f1=new File(dirname);
    	FilenameFilter only=new OnlyExt("txt");
    	String s[]=f1.list(only);
    	
    	for(int i=0;i<s.length;i++)
    		System.out.println(s[i]);
    	System.out.println("\n");
    	File[] f2=f1.listFiles();
    	File[] f3=f1.listFiles(only);
    	File[] f4=f1.listFiles(new FileFilterTest("txt"));
    	
    	p(f2); 
    	p(f3);
    	p(f4);
    }
    }
    




你可能感兴趣的:(Class)