|
Comments
Did you read today's front page stories & breaking news?
SYS-CON.TV
|
Java FAQ The Mysterious FilenameFilter Class
The Mysterious FilenameFilter Class
By: Jerry Ablan
Mar. 1, 1997 12:00 AM
Paul (paul@public.wh.hb.cn) (lweiden@erols.com) writes:
Listing 1 opens a directory and retrieves the names of the files in it. But what if you only want files of a certain type to be in your listing? You can always parse through the returned array and remove the unwanted files. But there is another, easier way! It is the FilenameFilter class. The FilenameFilter class is an interface that lives in the java.io package. Being an interface requires you to implement it in your own classes. This allows you maximum flexibility when using filters. The FilenameFilter interface contains a single method:
public boolean The File class contains a second overloaded list() method. This second one accepts a FilenameFilter implementor as an argument. When the list() method builds its array of names, it first calls the accept() method of the FilenameFilter implementor. If the accept() method returns true, the file name is placed into the array. If the accept() method returns false, the file name is discarded. A simple filter! Perhaps now you can see many different possibilities for filtering file names with this class. Listing 2 is an example filter that I cooked up. It is called ExtensionFilter and it filters files of a certain extension. It is not very robust and is extremely simple. Its purpose is to illustrate the use of the FilenameFilter class. This class simple stores the extension passed in during construction. You could at this point add error checking and cleanup of the extension string. The accept method implements the FilenameFilter interface and checks the argument name against the extension stored. This is done with the String method endsWith(). So how do you use this puppy? Easy! Below is a FilterTest class that uses the above ExtensionFilter and displays the files in the current directory. Reader Feedback: Page 1 of 1
Your Feedback
Latest Cloud Developer Stories
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week
Breaking Cloud Computing News
|
||||||||||||||||||||||||||||||||||||||||||||||||||||