How to Delete Files with Certain Extension in Java


In this example, let’s see how to delete files with certain extension in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator10Example { 
	public static void main(String[] args )
    {	
		File path = new File("example");
		File file = null;
		File[] filelist = path.listFiles();
		for (int i = 0; i < filelist.length; i++) 
		{
		    file = filelist[i];
		    if (file.getName().endsWith(".txt"))
			{
			    file.delete();
				System.out.println(file + " is deleted.");
			}
		}
    }
}

Output:

exampletest.txt is deleted.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments