Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files in a folder using Java

What I need to do if Search a folder say C:\example

I then need to go through each file and check to see if it matches a few start characters so if files start

temp****.txt tempONE.txt tempTWO.txt 

So if the file starts with temp and has an extension .txt I would like to then put that file name into a File file = new File("C:/example/temp***.txt); so I can then read in the file, the loop then needs to move onto the next file to check to see if it meets as above.

like image 992
Sii Avatar asked Jan 31 '11 15:01

Sii


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.

What is FilenameFilter in Java?

Interface FilenameFilter public interface FilenameFilter. Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in the list method of class File , and by the Abstract Window Toolkit's file dialog component.

What does files find do?

It searches or finds files from a file tree quickly. In the old days, we always use an error-prone recursive loop to walk a file tree. This Java 8 Files. find can save you a lot of time.


1 Answers

What you want is File.listFiles(FileNameFilter filter).

That will give you a list of the files in the directory you want that match a certain filter.

The code will look similar to:

// your directory File f = new File("C:\\example"); File[] matchingFiles = f.listFiles(new FilenameFilter() {     public boolean accept(File dir, String name) {         return name.startsWith("temp") && name.endsWith("txt");     } }); 
like image 110
jjnguy Avatar answered Sep 18 '22 01:09

jjnguy