NameFileFilter 类( NameFileFilter Class)

优质
小牛编辑
127浏览
2023-12-01

过滤名称的文件名。

Class 声明 (Class Declaration)

以下是org.apache.commons.io.filefilter.NameFileFilter类的声明 -

public class NameFileFilter
   extends AbstractFileFilter implements Serializable

NameFileFilter类的示例

这是我们需要解析的输入文件 -

Welcome to IoWiki. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤名为Input.txt的文件。

IOTester.java

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.NameFileFilter;
public class IOTester {
   public static void main(String[] args) {
      try {
         usingNameFileFilter();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }
   public static void usingNameFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile with name input.txt\n");
      String[] acceptedNames = {"input", "input.txt"};
      String[] filesNames = currentDirectory.list( new NameFileFilter(acceptedNames, IOCase.INSENSITIVE) );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出 (Output)

它将打印以下结果。

All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File with name input.txt
input.txt