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<Path> fileFilter = new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path entry) throws IOException { return matcher.matches(entry.getFileName()) && !Files.isDirectory(entry); } }; List<File> result = Lists.newArrayList(); try (DirectoryStream<Path> 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()); }
分享标题:JAVA正则表达式过滤文件的实现方法-创新互联
转载注明:https://www.cdcxhl.com/article46/dijghg.html
成都网站建设公司_创新互联,为您提供云服务器、微信公众号、网站排名、ChatGPT、外贸网站建设、定制开发
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联