Open In App

Java Program to Find/Delete Files Based on Extensions

Last Updated : 10 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Implement the FileNameFilter interface to list files with the given extension.
  2. 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

Spring Data JDBC Extensions
In this article, We will explore the realm of Spring Data JDBC extensions. Discover how they enhance the functionalities of the Spring Data JDBC module. These extensions offer a range of tools that enable developers to handle database interactions, with skill-making tasks, like simplifying queries enhancing security, and optimizing performance mana
3 min read
Spring Security - Role Based and Permission Based Access Control
Spring Security is a popular security framework for Java-based applications. It provides a wide range of security features including authentication and authorization. Authorization is determining whether a user is allowed to perform a specific action or access a specific resource. In Spring Security, authorization is implemented using access contro
11 min read
Java program to merge contents of all the files in a directory
Prerequisite : PrintWriter, BufferedReader. We are given a directory/folder in which n number of files are stored(We dont know the number of files) and we want to merge the contents of all the files into a single file lets say output.txt For the below example lets say the folder is stored at the path: F:\GeeksForGeeksFollowing are the steps: Create
2 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 file and after reading it, the contents inside it wou
4 min read
Java Program to Encrypt Password in Configuration Files
Passwords provide the first line of defense against unauthorized access to your computer and personal information. The stronger your password, the more protected your computer will be from hackers and malicious software. Every website or software application requires a password in order to authenticate the valid user. But while creating a password,
6 min read
Java program to merge two files alternatively into third file
Prerequisite : PrintWriter , BufferedReader Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt but merging should be done by line by line alternatively. The following are steps to merge alternatively. Create PrintWriter object for file3.txt Open BufferedReader for file1.txt Open Buffere
2 min read
Java program to merge two files into a third file
Prerequisite : PrintWriter , BufferedReader Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge. Create PrintWriter object for file3.txt Open BufferedReader for file1.txt Run a loop to copy each line of file1.txt to file3.txt Open BufferedReader for file
2 min read
Java Program to List all Files in a Directory and Nested Sub-Directories
Prerequisites: File class Given a main directory/folder, list all the files from it, and if this directory has other nested sub-directories, list files from them. It is pretty easy to observe a simple recursion pattern in the above problem. Algorithm : Create a File object for the main directory.Get an array of files for the main directory.If array
4 min read
Java program to merge two files alternatively into third file
Prerequisite : PrintWriter , BufferedReader Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt but merging should be done by line by line alternatively. The following are steps to merge alternatively. Create PrintWriter object for file3.txt Open BufferedReader for file1.txt Open Buffere
2 min read
JAR files in Java
A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform. In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image fi
3 min read
Article Tags :
Practice Tags :