Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing files in a directory matching a pattern in Java [duplicate]

Tags:

java

io

I'm looking for a way to get a list of files that match a pattern (pref regex) in a given directory.

I've found a tutorial online that uses apache's commons-io package with the following code:

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension) {   File directory = new File(directoryName);   return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null); } 

But that just returns a base collection (According to the docs it's a collection of java.io.File). Is there a way to do this that returns a type safe generic collection?

like image 558
Omar Kooheji Avatar asked Jan 20 '10 16:01

Omar Kooheji


People also ask

What does the files list () method in Java do?

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.

How to get all files with certain extension in a folder in Java?

walk to walk a file tree and stream operation filter to find files that match a specific file extension from a folder and its subfolders. try (Stream<Path> walk = Files. walk(Paths. get("C:\\test"), 1)) { //... }

How to find files with the file extension in Java?

From the Window's Start button, select "Search". Select "All files and folders" on the left. In the pop-up window, type in the file name (with . java properly) in "All or part of the file name".


2 Answers

See File#listFiles(FilenameFilter).

File dir = new File("."); File [] files = dir.listFiles(new FilenameFilter() {     @Override     public boolean accept(File dir, String name) {         return name.endsWith(".xml");     } });  for (File xmlfile : files) {     System.out.println(xmlfile); } 
like image 152
Kevin Avatar answered Oct 31 '22 04:10

Kevin


Since Java 8 you can use lambdas and achieve shorter code:

File dir = new File(xmlFilesDirectory); File[] files = dir.listFiles((d, name) -> name.endsWith(".xml")); 
like image 34
mr T Avatar answered Oct 31 '22 03:10

mr T