温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-06 18:32:57 来源:脚本之家 阅读:219 作者:QING____ 栏目:编程语言

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()); 
} 
 

2、适用于路径确定,文件名正则表达式的情况,这种正则表达式是JAVA支持的表达式,而非系统(unix)文件系统表达式(jdk8写法)

Path path = Paths.get("/data/logs"); 
Pattern pattern = Pattern.compile("^.+\\.log"); 
List<Path> 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()); 
} 
 

以上就是java 正则表达式过滤文件的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI