JAVA regular expression filter file implementation method

  • 2020-09-28 08:52:40
  • OfStack

JAVA regular expression filter file implementation method

Filtering a list of files with regular expressions sounds simple, but it takes a lot of effort to implement it with java. Here are two ways to do it

1. It is applicable to the case of regular expression in path determination and file name (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. Suitable for path determination and file name regular expressions, which are JAVA supported expressions and not unix file system expressions (jdk8).


Path path = Paths.get("/data/logs"); 
Pattern pattern = Pattern.compile("^.+\\.log"); 
List<Path> paths = Files.walk(path).filter(p -> { 
 // If it is not a regular file, filter it out  
 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()); 
} 
 

These are the examples of java regular expression filtering files. If you have any questions, please leave a message or go to our community for discussion. Thank you for reading, I hope you can help, thank you for your support to this site!


Related articles: