[Source Code]文件过滤

package com.mytest;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;

 

public class Test {
    public static void main( String[] args ) {
        File dir = new File(System.getProperty("user.dir"));
        System.out.println("Files under "+ dir.getAbsolutePath()+" :");
        File files[] = dir.listFiles(new FileFilter(){

            public boolean accept( File in ) {
                boolean fileOK = true;
                System.out.println("--->" + in.getAbsolutePath());
                fileOK &= in.getName().endsWith(".properties");
                return fileOK;
            }});
//        File files[] = dir.listFiles(new FilenameFilter(){
//
//            public boolean accept( File in, String filename ) {
//                boolean fileOK = true;
//                System.out.println("===> " + in.getAbsolutePath() + " ### " + filename);
//                fileOK &= filename.endsWith(".properties");
//               
//                return fileOK;
//            }});
        for(File file : files){
            System.out.println(file.getAbsolutePath());
        }
       
       
    }
}
 

 

 

 

=========================〉  实现类示例  《==============================

import java.io.File;
import java.io.FilenameFilter;
public class FileListFilter implements FilenameFilter {
private String name; // File name filter
private String extension; // File extension filter
// Constructor
public FileListFilter(String name, String extension) {
this.name = name;
this.extension = extension;
}
public boolean accept(File directory, String filename) {
boolean fileOK = true;
// If there is a name filter specified, check the file name
if (name != null) {
fileOK &= filename.startsWith(name);
}
// If there is an extension filter, check the file extension
if (extension != null) {
fileOK &= filename.endsWith(‘.’ + extension);
}
return fileOK;
}
}

摘自:

Ivor Horton’s Beginning Java™ 2,
JDK™ 5 Edition

你可能感兴趣的:([Source Code]文件过滤)