JAVA正则表达式过滤文件的实现方法-创新互联

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

专注于为中小企业提供成都网站设计、做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业沙坡头免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了1000多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

  正则表达式过滤文件列表,听起来简单,如果用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。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站托管运营