07 November 2008

Search a Folder for a File in Java

Java has some powerful mechanisms to search your server folders for files. I recently had a project where files were created on the server with partially random names, such as ABCD123__199518631844.jpg, where the ABCD123__ was the known portion of the filename. Later, I needed to find and delete these files. Some research revealed the FilenameFilter interface which contains an accept() method, returning a Boolean to indicate if the file meets a certain condition. In my case, I needed to have the filename begin with a specified string,

import java.io.FilenameFilter;
import java.io.File;

public class FileFilter implements FilenameFilter
private String _namePortion = "";

public boolean accept(File dir, String name)
return (name.startsWith(_namePortion));

public void setNamePortion(String value)
_namePortion = value;

I added the setNamePortion() method to set the string that will be tested. Then in the servlet, I added the following code to find and delete the file(s) that met the criteria,

File directory = new File(uploadDir);
filter.setNamePortion(aString + "__");

File fileList[] = directory.listFiles(filter);
String filePathToDelete = "";
File f = null;

for (int i=0; i < fileList.length; i++)
filePathToDelete = fileList[i].getAbsolutePath();
f = new File(filePathToDelete);
filePathToDelete = "";

No comments: