Java Program to Find/Delete Files Based on Extensions
Last Updated :
10 Aug, 2021
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.
Syntax:
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
Function Signature:
public String[] list()
public String[] list(FilenameFilter f)
Function Syntax:
file.list()
file.list(filter)
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.
Procedure:
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.
Example:
Java
// Java Program to find/delete files based on extensions
// Importing input output classes
import java.io.*;
// Class 1
// Main class
// To check for a file
class GFG {
// Member variables of this class
// File directory
private static final String FILE_DIRECTORY
= "/Users/mayanksolanki/Desktop/";
// File extension
private static final String FILE_EXTENSION = ".jpeg";
// Method of this class
public void deleteFile(String folder, String extension)
{
// Creating filter with given extension by
// creating an object of FileExtFilter
FileExtFilter filter = new FileExtFilter(extension);
// Now, creating an object of FIle class
File direction = new File(folder);
// Cresting an array if strings to
// list out all the file name
// using the list() with .txt extension
String[] list = direction.list(filter);
// Iterating over the array of strings
// using basic length() method
for (int i = 0; i < list.length; i++) {
// printing the elements
System.out.println(list[i]);
}
// Base condition check when array of strinfg is
// empty Then simply return
if (list.length == 0)
return;
File fileDelete;
// Now looking for the file in the
for (String file : list) {
String temp = new StringBuffer(FILE_DIRECTORY)
.append(File.separator)
.append(file)
.toString();
// Storing the file
fileDelete = new File(temp);
// Checking whether the file is deleted
boolean isdeleted = fileDelete.delete();
// Print true if file is deleted
System.out.println("file : " + temp
+ " is deleted : "
+ isdeleted);
}
}
// Method 2
// Main driver method
public static void main(String args[])
{
// Calling the deleteFile() method over the file
// FileCheker() method to check existence for the
// file
// Delete the file with FILE_EXTENSION from
// FILE_DIRECTORY using the deleteFile() method s
// created above
new GFG().deleteFile(FILE_DIRECTORY, FILE_EXTENSION);
}
}
// Class 2
// Helper class
// Which in itself is implementing FilenameFilter Interface
class FileExtFilter implements FilenameFilter {
// Extension
private String extension;
// Comparator
public FileExtFilter(String extension)
{
// This keyword refers to current object itself
this.extension = extension;
}
public boolean accept(File directory, String name)
{
// Returning the file name along with the file
// extension type
return (name.endsWith(extension));
}
}
Output:
Similar Reads
Java Program to Delete a directory The class named java.io.File represents a file or directory (path names) in the system. This class provides methods to perform various operations on files/directories. The delete() method of the File class deletes the files and empty directory represented by the current File object. If a directory i
2 min read
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 retur
3 min read
How to Delete Temporary File in Java? In java, we have a java.io package that provides various methods to perform various operations on files/directories. Temporary files are those files that are created for some business logic or unit testing, and after using these files you have to make sure that these temporary files should be delet
2 min read
Java Program to Check if a Directory is Empty or Not The list() method defined in class java.io.File which is used to obtain the list of files and folders(directories) present in the specified directory defined by its pathname. The list of files is stored in an array of string. If the length of an array is greater than 0, then the specified directory
3 min read
Java Program to Read and Print All Files From a Zip File A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Â Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip fi
4 min read
Java Program to Display all the Directories in a Directory The directory is the organizing structure of the computer file system which is not only responsible for storing files but also to locate them on the memory. File organization structure is a hierarchical structure involving parent and child relationships just like what is there in tree data structure
3 min read
Comparing Path of Two Files in Java The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the program is requesting the file modification access which is already in use by another program. To compare the path of the file, com
2 min read
Java Program to Get the Basic File Attributes Basic File Attributes are the attributes that are associated with a file in a file system, these attributes are common to many file systems. In order to get the basic file attributes, we have to use the BasicFileAttributes interface. This interface is introduced in 2007 and is a part of the nio pack
3 min read
Java Program to Create a Temporary File A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement. Type of Fi
6 min read
How to Extract File Extension From a File Path String in Java? In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Pr
5 min read