Java Program to Find/Delete Files Based on Extensions
We can use FilenameFilter in Java to override the accept(File dir, String name) method to execute the file filtering operation. Filename interface has a method accept(). It checks whether a given file should be included in a list of files. We can check each file in the passed directory by implementing this method. If the file has the required extension, then it is included otherwise discarded.
accept(File dir, String name)
Now the next things that come into play is how to include the files in a list with the given extension, for that there is a File.list() method that takes the FilenameFilter instance. the list Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfies the specified filter. So let us discuss this function in detail to get a better understanding while dealing with the files.
The list() method is a part of File class. The function returns an array of the string denoting the files in a given abstract pathname if the pathname is a directory else returns null. The function is an overloaded function. One of the function does not have any parameter and the other function takes FilenameFilter object as a parameter as described below
public String list() public String list(FilenameFilter f)
Parameters: The function is an overloaded function. One of the function does not have any parameter and the other function takes FilenameFilter object as a parameter
Return value: The function returns a string array, or a null value if the file object is a file.
Exception: This method throws Security Exception if the function is not allowed to write access to the file.
We will follow two steps to delete files based on extensions:
- Implement the FileNameFilter interface to list files with the given extension.
- Iterate through those files to delete them using the delete() method.