FilenameFilter achieved with DirFilter, capable of expression to filter the file name in the directory by positive;
It may also be implemented in other ways other filters, similar to the filter size, type, etc.!
class DirFilter implements FilenameFilter{ private Pattern pattern; public DirFilter(String regex) { pattern = Pattern.compile(regex); } @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }
- Get all the files:
Regular expression: "[\\ s \\ S] *" indicates the character of any length:
@Test public void DirFileter () { File path = new new File ( "." ); String [] List; List = path.list ( new new DirFilter ( "[S \\ \\ S] *" )); // List path.list = (); // no way to obtain a regular expression Arrays.sort (List, String.CASE_INSENSITIVE_ORDER); for (String dirItem: List) { System.out.println (dirItem); } }
result:
- Obtain a specific file: Regular expression: "[az] *"
@Test public void DirFileter2(){ File path = new File("."); String[] list; list = path.list(new DirFilter("[a-z]*")); Arrays.sort(list,String.CASE_INSENSITIVE_ORDER); for(String dirItem : list){ System.out.println(dirItem); } }
Results: Get all lowercase letters in file names