Java Program to Search for a File in a Directory
Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java.io.File.list() method. This method is very useful when we want to find files with a specific extension within a folder.
- Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface.
- The accept() method takes two arguments of which the first one is the directory name and the second one is the filename.
- The accept() method returns true if the filename starts with the specified initials else returns false.
- The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search.
- The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user.
- The list() method is invoked on the dir object which returns an array of files that satisfy the condition.
- The array is iterated over and the name of the required files are printed to the output screen.
- The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array.
- Each file in the ‘flist’ array is checked against the required filename.
- If a match is found it is printed on the screen.
This method is a bit different from the previous one as the user needs to specify the exact name of the file in this case.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.