欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java核心编程之文件过滤类FileFilter和FilenameFilter

程序员文章站 2024-02-22 12:25:04
本文实例为大家分享了文件过滤类filefilter和filenamefilter,供大家参考,具体内容如下 1.filefilter package test;...

本文实例为大家分享了文件过滤类filefilter和filenamefilter,供大家参考,具体内容如下

1.filefilter

package test;

import java.io.file;
import java.io.filefilter;

public class filefiltertest implements filefilter {
  
  
  private string extension;
  
  public filefiltertest(string extension) {

    this.extension = extension;
  }
  /**
   * 
   */
  @override
  public boolean accept(file pathname) {
      
    if(pathname.isdirectory()){
      return false;
    }
    
    string name = pathname.getname();
    int num = name.lastindexof(".");
    if(num == -1){
      return false;
    }
    if(name.length()-1 == num){
      return false;
    } else {
    
      return extension.equals(name.substring(num+1));
    }
  }
  
  
  public static void main(string[] args) {
    
    file path = new file("e:\\书籍\\java 编程");
    //获得过滤对象
    filefiltertest ft = new filefiltertest("pdf");
    
    file[] files = path.listfiles(ft);
    
    for (int i = 0; i < files.length; i++) {
      system.out.println(files[i].getabsolutepath());
    } 
    
  }

}

2.filenamefilter

package test;

import java.io.file;
import java.io.filenamefilter;

public class filenamefiltertest implements filenamefilter {
  
  //判断图片是否格式是否是 gif
  private boolean isgif(string filename){
    if(filename.tolowercase().endswith(".gif")){
      return true;
    } else {
      return false;
    }
    
  }
  //判断图片是否格式是否是 jpg
  private boolean isjpg(string filename){
    if(filename.tolowercase().endswith(".jpg")){
      return true;
    } else {
      return false;
    }
    
  }
  //判断图片是否格式是否是 png
  private boolean ispng(string filename){
    if(filename.tolowercase().endswith(".png")){
      return true;
    } else {
      return false;
    }
    
  }
  
  

  @override
  public boolean accept(file dir, string name) {
    return (isgif(name)||isjpg(name)||ispng(name));
  }
  
  public static void main(string[] args) {
    file path = new file("c:\\img");
    //获得过滤对象
    filenamefiltertest ft = new filenamefiltertest();
    
    file[] f = path.listfiles(ft);
    
    for (int i = 0; i < f.length; i++) {
      file file = f[i];
      
      system.out.println(file.getabsolutepath());
      
    }
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。