Home  >  Article  >  Java  >  How to use FileFilter method to search files in Java

How to use FileFilter method to search files in Java

王林
王林forward
2023-05-01 19:01:051565browse

FileFilter is included in numerous add-ons to Java Development Kit (JDK) 1.2. Its main function is to detect whether the file exists. The biggest difference between FileFilter and its predecessor FilenameFilter is that FileFilter provides access methods for file objects, while FilenameFilter works according to directories and file names.

For example, FileFilter is like this:

boolean accept(File file);

And FilenameFilter is as follows Looks like:

boolean accept(File directory, String name);

A simple example is to search for a specific file extension. You can use FilenameFilter, but the result will make it difficult for you to determine whether it is a folder or a file. To solve this problem, you need to use file objects. That is, use FileFilter.

The following is the code of ExtensionFileFilter:

package com.generationjava.io.find;

The above is used in the following examples ExtensionFileFilter code:

...
String dir = "...";   // directory of your choice
File file = new File(dir);
File[] files = file.listFiles(new ExtensionFileFilter("cfg"));

FileFilter is actually derived from javax.swing.filechooser.FileFilter, javax.swing.filechooser.FileFilter is an abstract class that uses JFileChoosers.

The above is the detailed content of How to use FileFilter method to search files in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete