regex
List files with regular expression filtering
This is an example of how to list files using regular expression filtering. In order to list Files using regular expressions to filter them we have set the example below:
- Class
DirFilter
implements the FilenameFilter. It has a Pattern that is initialized by compiling a String regular expression to a Pattern, usingcompile(String regex)
API method of Pattern. It also has a methodboolean accept(File dir, String name)
. The method reads a file name and creates a new File, and then gets the file name, using getName() API method. It creates a new Matcher from the pattern and the given String withmatcher(CharSequence input)
API method of Matcher and tries to match the entire region against the pattern, withmatches()
API method of Matcher. - Class
AlphabeticComparator
implements the Comparator and has a method,int compare(Object o1, Object o2)
. The method gets two objects and returns true if the String representation of the objects converted to characters in lower case are equal, according to thecompareTo(String anotherString)
API method of String. - We create a new File and get the array of strings naming the files and directories in the directory denoted by a new
DirFilter
initialized with a specified pattern. - We use
sort(T[], Comparator<? super T>)
API method of Arrays to sort the array according to the AlphabeticComparator
and print the results.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.Comparator; import java.util.regex.Pattern; public class DirList { public static void main(String[] args) { File filePath = new File("."); String[] list; list = filePath.list(new DirFilter("bu.+")); Arrays.sort(list, new AlphabeticComparator()); for (int i = 0; i < list.length; i++) System.out.println(list[i]); } } class DirFilter implements FilenameFilter { private Pattern pattern; public DirFilter(String reg) { pattern = Pattern.compile(reg); } @Override public boolean accept(File dir, String name) { // Strip path information, search for regex: return pattern.matcher(new File(name).getName()).matches(); } } class AlphabeticComparator implements Comparator { @Override public int compare(Object o1, Object o2) { String str1 = (String) o1; String str2 = (String) o2; return str1.toLowerCase().compareTo(str2.toLowerCase()); } }
Output:
build
build.xml
This was an example of how to list files using regular expression filtering in Java.