Using FileFilter to search for files in Java

Source: Internet
Author: User

FileFilter is included in the Java Development Kit (JDK) 1.2 of numerous attachments. His main function is to detect whether a file exists. FileFilter and his predecessor FilenameFilter the only difference is that FileFilter provides access to file objects, and FilenameFilter works by directory and file name.

For example, FileFilter is like this:

Boolean Accept (file file);

And FilenameFilter is the following:

Boolean Accept (File directory, String name);

A simple example is searching for a specific file name extension. You can use FilenameFilter, but the results will make it hard to tell whether it's a folder or a file. To solve this problem, you need to use a file object. That is to use FileFilter bar.

Here's the code for Extensionfilefilter:

Package com.generationjava.io.find;
Import Java.io.file;import java.io.FileFilter;
public class Extensionfilefilter implements FileFilter {
private String extension;
Public extensionfilefilter (String extension) {
this.extension = extension;
}
Public boolean accept (file file) {
if (file.isdirectory ()) {return
false;
}
String name = File.getname ();
Find the Lastint idx = Name.lastindexof (".");
if (index = = 1) {return
false;
}
elseif (index = = Name.length ()-1) {return
false;
}
Els e {return
this.extension.equals (name.substring (index+1));
}
}

The following example uses the above Extensionfilefilter code:

...  String dir = "...";
Directory of your Choicefile file = new file (dir);
file[] files = file.listfiles (new Extensionfilefilter ("CFG"));
The files variable are now c:\*.cfg if @ #dir @# are c:\//that are, all the files in the
specified directory ending in *. Cfg...

FileFilter is actually derived from Javax.swing.filechooser.FileFilter, Javax.swing.filechooser.FileFilter is an abstract class that uses jfilechoosers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.