最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JAVA正则表达式过滤文件的实现方法
时间:2022-06-29 01:21:11 编辑:袖梨 来源:一聚教程网
JAVA正则表达式过滤文件的实现方法
正则表达式过滤文件列表,听起来简单,如果用java实现,还真需要一番周折,本文简析2种方式
1、适用于路径确定,文件名时正则表达式的情况(jdk6的写法)
String filePattern ="/data/logs/.+.log";
File f =newFile(filePattern);
File parentDir = f.getParentFile();
String regex = f.getName();
FileSystem FS = FileSystems.getDefault();
finalPathMatcher matcher = FS.getPathMatcher("regex:"+ regex);
DirectoryStream.Filter fileFilter =newDirectoryStream.Filter() {
@Override
publicbooleanaccept(Path entry)throwsIOException {
returnmatcher.matches(entry.getFileName()) && !Files.isDirectory(entry);
}
};
List result = Lists.newArrayList();
try(DirectoryStream stream = Files.newDirectoryStream(parentDir.toPath(), fileFilter)) {
for(Path entry : stream) {
result.add(entry.toFile());
}
}catch(IOException e) {
e.printStackTrace();
}
for(File file : result) {
System.out.println(file.getParent() +"/"+ file.getName());
}
2、适用于路径确定,文件名正则表达式的情况,这种正则表达式是JAVA支持的表达式,而非系统(unix)文件系统表达式(jdk8写法)
Path path = Paths.get("/data/logs");
Pattern pattern = Pattern.compile("^.+.log");
List paths = Files.walk(path).filter(p -> {
//如果不是普通的文件,则过滤掉
if(!Files.isRegularFile(p)) {
returnfalse;
}
File file = p.toFile();
Matcher matcher = pattern.matcher(file.getName());
returnmatcher.matches();
}).collect(Collectors.toList());
for(Path item : paths) {
System.out.println(item.toFile().getPath());
}
相关文章
- 逆战未来枪械大全 逆战未来枪械稀有度等级与获取方式详解 07-19
- 逆战未来新手攻略 逆战未来萌新入门避坑指南 07-19
- "无醇啤酒"是完全不含酒精吗 蚂蚁庄园1月17日答案早知道 07-19
- "太常寺"是古代掌管什么事务的机构 蚂蚁新村1月16日答案 07-19
- 四川名菜"开水白菜"就是用开水炖白菜吗 蚂蚁庄园1月17日答案早知道 07-19
- 蚂蚁新村今天正确答案1.16 07-19