java 提供的文件过滤类FilenameFilter使用

 场景:在文件目录dir/下,存在一个文件名称为blk_XXXXXXX,找出该名称对应的元文件,名称为blk_XXXXXXX_XXX.meta

 

 

  private static File findMetaFile(final File blockFile) throws IOException {

    final String prefix = blockFile.getName() + "_";

    final File parent = blockFile.getParentFile();

    File[] matches = parent.listFiles(new FilenameFilter() {  //列出dir目录下的所有符合accept条件的文件,

      public boolean accept(File dir, String name) {

        return dir.equals(parent)

            && name.startsWith(prefix) && name.endsWith(“.meta”);  

      }

    });

 

    if (matches == null || matches.length == 0) {

      throw new IOException("Meta file not found, blockFile=" + blockFile);

    }

    else if (matches.length > 1) {

      throw new IOException("Found more than one meta files: " 

          + Arrays.asList(matches));

    }

    return matches[0];

  }

 

你可能感兴趣的:(java 提供的文件过滤类FilenameFilter使用)