Home> Java> javaTutorial> body text

How to implement regular expression filtering files in Java

黄舟
Release: 2017-09-02 10:34:07
Original
2097 people have browsed it

这篇文章主要介绍了JAVA正则表达式过滤文件的实现方法的相关资料,希望通过本文大家能够掌握理解这部分内容,需要的朋友可以参考下

JAVA正则表达式过滤文件的实现方法

正则表达式过滤文件列表,听起来简单,如果用java实现,还真需要一番周折,本文简析2种方式

1、适用于路径确定,文件名时正则表达式的情况(jdk6的写法)

String filePattern = "/data/logs/.+\\.log"; File f = new File(filePattern); File parentDir = f.getParentFile(); String regex = f.getName(); FileSystem FS = FileSystems.getDefault(); final PathMatcher matcher = FS.getPathMatcher("regex:" + regex); DirectoryStream.Filter fileFilter = new DirectoryStream.Filter() { @Override public boolean accept(Path entry) throws IOException { return matcher.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()); }
Copy after login

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)) { return false; } File file = p.toFile(); Matcher matcher = pattern.matcher(file.getName()); return matcher.matches(); }).collect(Collectors.toList()); for(Path item : paths) { System.out.println(item.toFile().getPath()); }
Copy after login


The above is the detailed content of How to implement regular expression filtering files in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!