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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

}<br />

try {<br />

FileDialog fd = new FileDialog(new Frame("Not important"),<br />

"Please select a file in the directory you want to list:",<br />

FileDialog.LOAD);<br />

fd.setVisible(true);<br />

if (fd.getDirectory() == null) return;<br />

DirList dl = new DirList(fd.getDirectory());<br />

dl.list();<br />

fd.dispose();<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

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

A filename filter can be attached to a file dialog via the dialog's setFilenameFilter()<br />

method:<br />

public synchronized void setFilenameFilter(FilenameFilter filter)<br />

Once a file dialog's filename filter is set, it should only display files that pass through the<br />

filter. In practice, however, filename filters in file dialogs are only truly reliable on Unix.<br />

Many early Mac VMs do not really support this feature, though some of the more recent ones<br />

do. And Windows is almost congenitally unable to support it, because Windows' native file<br />

chooser dialog can only filter by file extension. The problem is that filename filters are<br />

designed for the Motif API. The Windows and Macintosh APIs provide different ways of<br />

achieving the same effect.<br />

Example 13.2 demonstrates the use of a filename filter in a file dialog. The TextChooser<br />

class implements the FilenameFilter interface. The main() method calls the getFile()<br />

method to load a file. Once a file is loaded, it's written on System.out. The getFile()<br />

method uses a file dialog to ask the user what file should be written. A new TextChooser<br />

object is passed to the file dialog's setFilter() method to indicate that this class's accept()<br />

method should be used to filter files. The accept() method accepts files ending in .text, .txt,<br />

.java, .jav, .html , and .htm; all others are rejected.<br />

Example 13.2. The TextChooser Program<br />

import java.io.*;<br />

import java.awt.*;<br />

import com.macfaq.io.*;<br />

public class TextChooser implements FilenameFilter {<br />

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

try {<br />

File f = getFile();<br />

if (f == null) return;<br />

FileInputStream fin = new FileInputStream(f);<br />

StreamCopier.copy(fin, System.out);<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

310

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

Saved successfully!

Ooh no, something went wrong!