23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Java</strong> I/O<br />

the following lines of code list HTML files in the /public/html/javafaq directory using<br />

the HTMLFilter of Example 12.6.<br />

File dir = new File("/public/html/javafaq");<br />

File[] htmlFiles = dir.listFiles(new HTMLFilter());<br />

for (int i = 0; i < htmlFiles.length; i++) {<br />

System.out.println(htmlFiles[i]);<br />

}<br />

12.5 File Filters<br />

<strong>Java</strong> 2 adds a new java.io.FileFilter interface that's very similar to FilenameFilter:<br />

public abstract interface FileFilter // <strong>Java</strong> 2<br />

The accept() method of FileFilter takes a single File object as an argument, rather than<br />

two strings giving the directory and path:<br />

public boolean accept(File pathname) // <strong>Java</strong> 2<br />

Example 12.7 is a filter that only passes HTML files. Its logic is essentially the same as the<br />

filter of Example 12.6.<br />

Example 12.7. HTMLFileFilter<br />

import java.io.*;<br />

public class HTMLFileFilter implements FileFilter {<br />

}<br />

}<br />

public boolean accept(File pathname) {<br />

if (pathname.getName().endsWith(".html")) return true;<br />

if (pathname.getName().endsWith(".htm")) return true;<br />

return false;<br />

This class appears as an argument in one of the listFiles() methods of java.io.File:<br />

public File[] listFiles(FileFilter filter) // <strong>Java</strong> 2<br />

Example 12.8 uses the HTMLFileFilter to list the HTML files in the current working<br />

directory.<br />

Example 12.8. List HTML Files<br />

import java.io.*;<br />

public class HTMLFiles {<br />

public static void main(String[] args) {<br />

File cwd = new File(System.getProperty("user.dir"));<br />

File[] htmlFiles = cwd.listFiles(new HTMLFileFilter());<br />

300

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!