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

时间:2022-08-30 21:49:12

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

1.FileFilter

java" id="highlighter_631647">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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());
      
    }
  }
 
}

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

原文链接:http://www.cnblogs.com/wwyx-xi/archive/2017/08/24/7423599.html