In this section we will be showing instructions on how to delete a file in consideration with the file extension. Consider a scenario when the requirements is for us to delete all files with extension .log under a folder. This is very helpful knowledge especially during design of maintenance architecture in corporate scenario.
Delete files with file extension .log in a folder using FileNameFilter
This is very easy we just have to find a way to list all files with .log extension under a folder. This can be accomplished by method listFiles of File class under java.io package. The listFiles as of JavaSe 7, is accepting a FileNameFileFilter. FilenameFilter is an interface which is used to filter filenames. Since it s an interface we are required to implement method accept(File dir, String name). Method accept returns a boolean which we can put logic in filtering the filename. Please see below for the source code that implements the FilenameFilter class.
package com.javatutorialhq.tutorial; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DeleteFileWithExtension { /** * This java sample code shows * how to delete file with specific extension using FileNameFilter * Property of javatutorialhq.com * All Rights Reserved * Version 1.0 * 07/26/2012 */ public static void main(String[] args) { File file = new File("C:\\temp\\files"); //check first if supplied file name is a folder if(file.isDirectory()){ List listFile = new ArrayList<>(); listFile = Arrays.asList(file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".log"); } })); for(File f:listFile){ System.out.println("Deleting " + f.getAbsolutePath()); f.delete(); } } else{ //Flagging down that the filename specified is not a directory System.out.println("file:"+file.getAbsolutePath()+" is not a directory"); } } }
Here is a sample output upon running the program
Deleting C:\temp\files\another.log Deleting C:\temp\files\copy.log Deleting C:\temp\files\logger.log Deleting C:\temp\files\test1.log Deleting C:\temp\files\tester.log