import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class TestParseJson { @Test public void test() throws IOException { Path startingDir = Paths.get("f:\\temp"); FindFileVisitor filterFilesVisitor= new FindFileVisitor(".wav","\\d+{13}"); Files.walkFileTree(startingDir, filterFilesVisitor); List<Path> files = filterFilesVisitor.getFilenameList(); System.out.println(files); } }
import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.LinkedList; import java.util.List; class FindFileVisitor extends SimpleFileVisitor<Path> { private List<Path> filenameList = new LinkedList<>(); private String fileSuffix = null; private String pattern = null; public FindFileVisitor(String fileSuffix) { this.fileSuffix = fileSuffix; } public FindFileVisitor(String fileSuffix,String pattern) { this(fileSuffix); this.pattern = pattern; } public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { String absPath = file.toString(); Path fileName = file.getFileName(); if (absPath.endsWith(fileSuffix)) { if(pattern != null) { //正则表达式+文件后缀名匹配整个文件名 //例如pattern \\d{13} 后缀.wav组成新的表达式 "\\d{13}\\.wav" if(!fileName.toString().matches(pattern + fileSuffix)) { return FileVisitResult.CONTINUE; } } filenameList.add(file.normalize()); } return FileVisitResult.CONTINUE; } public List<Path> getFilenameList() { return filenameList; } }
输出结果
来源:https://www.cnblogs.com/passedbylove/p/11510196.html