集册 Java实例教程 按全局模式搜索文件

按全局模式搜索文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

462
通过Glob模式搜索文件

import java.io.IOException;
/**
n o w  j a v a  . c o m 提供 
**/

import java.nio.file.FileSystems;

import java.nio.file.FileVisitOption;

import java.nio.file.FileVisitResult;

import java.nio.file.FileVisitor;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.PathMatcher;

import java.nio.file.Paths;

import java.nio.file.attribute.BasicFileAttributes;

import java.util.EnumSet;


public class Main {

  public static void main(String[] args) throws Exception {/** 来自 n o w j a v a . c o m - 时  代  Java**/

    String glob = "*.jpg";

    Path fileTree = Paths.get("C:/folder1/");

    Search walk = new Search(glob);

    EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);


    Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);


  }

}


class Search implements FileVisitor {


  private final PathMatcher matcher;


  public Search(String glob) {

    matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);

  }


  void search(Path file) throws IOException {

    Path name = file.getFileName();

    if (name != null && matcher.matches(name)) {

      System.out.println("Searched file was found: " + name + " in "

          + file.toRealPath().toString());

    }

  }


  @Override

  public FileVisitResult postVisitDirectory(Object dir, IOException exc)

      throws IOException {

    System.out.println("Visited: " + (Path) dir);

    return FileVisitResult.CONTINUE;

  }


  @Override

  public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs)

      throws IOException {

    return FileVisitResult.CONTINUE;

  }


  @Override

  public FileVisitResult visitFile(Object file, 
展开阅读全文