Home > Java, Java 1.6 Tutorial > Using FileFilter in Java

Using FileFilter in Java


We moved. Please visit this link for this post.

 

 

 

What need to do when you want to filter files by extensions in catalog.

There are 2 ways:

implements FileFilter or FilenameFilter.

I am going to show how to do this with FileFilter.

FileFilter is an interface for filtering File objects based on their names or other information.

Example:

class ProjectFilter implements FileFilter {

private String[] extension = {"java", "xml"};

@Override

public boolean accept(File pathname) {

if (pathname.isDirectory()) {

return true;

}

String name = pathname.getName().toLowerCase();

for (String anExt : extension) {

if (name.endsWith(anExt)) {

return true;

}

}

return false;

}

}

Now just use ProjectFilter object in listFiles method.

Example:

File dir = new File("C:/sample_dir");

File[] files = dir.listFiles(new ProjectFilter())

In this case in array files will presents files with extensions java and xml.

Full example:

import java.io.File;
import java.io.FileFilter;
/**
* Main class which shows how to use name filter feature
* @author FaYna Soft Labs
*/
public class Main {
public static void main(String[] args) {
File dir = new File("D:/project/sample_dir");
File[] files = dir.listFiles(new ProjectFilter());
for (File f : files) {
System.out.println(f.getAbsolutePath());
}
}
private static class ProjectFilter implements FileFilter {
private String[] extension = {"java", "xml"};
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
String name = pathname.getName().toLowerCase();
for (String anExt : extension) {
if (name.endsWith(anExt)) {
return true;
}
}
return false;
}
}
}

File filtering is very simple operation in Java.

For this post I used JDK 6.

Advertisements
Categories: Java, Java 1.6 Tutorial
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: