或可替代的Java 7的方式
public List<File> getFiles(String path){
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:.txt");
List<File> resultFiles = new ArrayList<File>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(path))) {
for (Path pathEntry : directoryStream) {
if (matcher.matches(pathEntry)) {
resultFiles.add(pathEntry.toFile());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
return resultFiles;
}
編輯:只注意到子目錄的要求,堅持到Java 7的方法中,該解決方案地址子目錄,以及。
public List<File> getFiles(String path){
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:.txt");
final List<File> resultFiles = new ArrayList<File>();
try {
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
resultFiles.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
return resultFiles;
}