FileFilter, FilenameFilter用法和文件排序


FileFilter和FilenameFilter這兩個類的用法都很簡單,都只有一個方法


FileFilter
/**
* @param pathname The abstract pathname to be tested
*/

boolean accept(File pathname)
用法示例:
import java.io.File;
import java.io.FileFilter;

public class Main {

  public static void main(String[] args) {

    File cwd = new File(System.getProperty( "user.dir"));
    File[] htmlFiles = cwd.listFiles( new HTMLFileFilter());
    for ( int i = 0; i < htmlFiles.length; i ++) {
      System.out.println(htmlFiles[i]);
    }
  }
}

class HTMLFileFilter implements FileFilter {

  public boolean accept(File pathname) {

    if (pathname.getName().endsWith( ".html"))
      return true;
    if (pathname.getName().endsWith( ".htm"))
      return true;
    return false;
  }
}
 
FilenameFilter
 
/**
* @param dir - the directory in which the file was found.
* @param name - the name of the file.
*/

boolean accept(File dir,  String name)

 

用法示例:
import java.io.File;
import java.io.FilenameFilter;

class ExtensionFilter implements FilenameFilter {
  String ext;

  public ExtensionFilter(String ext) {
    this.ext = "." + ext;
  }

  public boolean accept(File dir, String name) {
    return name.endsWith(ext);
  }
}

public class Main {
  public static void main(String args[]) {
    String dirname = "/java";
    File f1 = new File(dirname);
    FilenameFilter only = new ExtensionFilter( "html");
    String s[] = f1.list(only);
    for ( int i = 0; i < s.length; i ++) {
      System.out.println(s[i]);
    }
  }
}
 
文件排序
排序規則:目錄排在前面,按字母順序排序文件列表
 
List <File > files = Arrays.asList( new File( "<目錄>").listFiles());
Collections.sort(files, new Comparator <File >(){
    @Override
    public int compare(File o1, File o2) {
    if(o1.isDirectory() && o2.isFile())
         return - 1;
    if(o1.isFile() && o2.isDirectory())
             return 1;
    return o1.getName().compareTo(o2.getName());
    }
});

for(File f : files)
    System.out.println(f.getName());
 

from: www.hilyb.com

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM