A Java FileFilter example

Summary: A Java FileFilter example, including a complete implementation of a Java FileFilter class.

I don't have much time for discussion today, but here's the source code for a Java FileFilter example I created in a text editor I wrote named "Jelly":

package com.devdaily.jelly.model;

import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

public class RGAFileFilter extends FileFilter
{

  // Accept all directories and all .tex and .latex files.
  public boolean accept(File f)
  {
    if (f.isDirectory())
    {
        return true;
    }

    String extension = getExtension(f);
    if (extension != null)
    {
      //if (extension.equals("tex") || extension.equals("latex") || extension.equals("rga") )
      if ( extension.equals("rga") )
      {
          return true;
      }
      else
      {
          return false;
      }
    }

    return false;
  }

  // The description of this filter
  public String getDescription()
  {
    return "RGA Files (.rga)";
  }

  public static String getExtension(File f)
  {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');

    if (i > 0 &&  i < s.length() - 1) {
        ext = s.substring(i+1).toLowerCase();
    }
    return ext;
  }
}

As you can see from the code, I currently use a filename extension of ".rga", but I also used to use file extensions like ".tex" and ".latex".

Sorry, no other discussion here today ... if you're here, I hope you know why you need a Java FileFilter example, and just wanted to see an implementation like this.

Permalink

Sorry, i read your article now and it makes me a little bit sad. There is two things, i have to say/write to you. ;)

Method getExtension logically not belongs to class FileFilter, but FileUtils or something like that. So it should be private or protected or place it somewhere else.

And i`d usually rather use String.endsWith(String) for this purpose. It`s faster and simple way to do that.

But it is nice blog, respect! :)

Thanks for your comments. I agree, the method getExtension belongs to a "file utils" class, and in fact, that's where it was. I just moved it here to make this example complete.

String.endsWith is also a nice touch, thank you. Really, if I were to write this again today, I'd probably use the Apache FileUtils libraries, but I wrote this a long time ago.

All the best, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.