Wednesday, May 19, 2010

Looking for a file in a Folder

The java.io.FileFilter interface can be used to filter an array of files obtained when looking inside a directory.

An example implementation of FileFilter

class JarFileFilter implements FileFilter
{
public boolean accept(File file)
{
if(file.getName().toLowerCase().endsWith("jar"))
{
return true;
}
return false;
}
}

The above implementation class narrows down the list of files to only jar files.

This filter can be used when looking into a directory using java.io.File.

example snippet:

String myDirectoryLoc = "c:\myjars";
File myFolder = new File(myDirectoryLoc);

if(myFolder.isDirectory())
{
File[] myjars = myFolder.listFiles(new JarFileFilter);

if(myjars != null)
{
for (File f : myjars )
{
System.out.println("file: " + f.getName());
}
}
}

On successful execution you will get only the jar files in the specified folder.

Hope this is useful.

Cheers
Vinay