The FileFilter interface is very similar to FilenameFilter:
public abstract interface FileFilter
The accept( ) method of FileFilter takes a single File object as an argument, rather than two strings giving the directory and path:
public boolean accept(File pathname)
Example 17-8 is a filter that only passes HTML files. Its logic is essentially the same as the filter of Example 17-7.
Example 17-8. HTMLFileFilter
import java.io.*; public class HTMLFileFilter implements FileFilter { public boolean accept(File pathname) { if (pathname.getName( ).endsWith(".html")) return true; if (pathname.getName( ).endsWith(".htm")) return true; return false; } } |
This class appears as an argument in one of the listFiles( ) methods of java.io.File:
public File[] listFiles(FileFilter filter)
Example 17-9 uses the HTMLFileFilter to list the HTML files in the current working directory.
Example 17-9. List HTML files
import java.io.*; public class HTMLFiles { public static void main(String[] args) { File cwd = new File(System.getProperty("user.dir")); File[] htmlFiles = cwd.listFiles(new HTMLFileFilter( )); for (int i = 0; i < htmlFiles.length; i++) { System.out.println(htmlFiles[i]); } } } |
Basic I/O
Introducing I/O
Output Streams
Input Streams
Data Sources
File Streams
Network Streams
Filter Streams
Filter Streams
Print Streams
Data Streams
Streams in Memory
Compressing Streams
JAR Archives
Cryptographic Streams
Object Serialization
New I/O
Buffers
Channels
Nonblocking I/O
The File System
Working with Files
File Dialogs and Choosers
Text
Character Sets and Unicode
Readers and Writers
Formatted I/O with java.text
Devices
The Java Communications API
USB
The J2ME Generic Connection Framework
Bluetooth
Character Sets