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.

}<br />

}<br />

// Work around annoying AWT non-daemon thread bug.<br />

System.exit(0);<br />

public boolean accept(File dir, String name) {<br />

}<br />

if (name.endsWith(".java")) return true;<br />

else if (name.endsWith(".jav")) return true;<br />

else if (name.endsWith(".html")) return true;<br />

else if (name.endsWith(".htm")) return true;<br />

else if (name.endsWith(".txt")) return true;<br />

else if (name.endsWith(".text")) return true;<br />

return false;<br />

public static File getFile() throws <strong>IO</strong>Exception {<br />

}<br />

// dummy Frame, never shown<br />

Frame parent = new Frame();<br />

FileDialog fd = new FileDialog(parent, "Please choose a file:",<br />

FileDialog.LOAD);<br />

fd.setFilenameFilter(new TextChooser());<br />

fd.show();<br />

// Program stops here until user selects a file or cancels.<br />

String dir = fd.getDirectory();<br />

String file = fd.getFile();<br />

// Clean up our windows, they won't be needed again.<br />

parent.dispose();<br />

fd.dispose();<br />

if (dir == null || file == null) { // User cancelled the dialog.<br />

return null;<br />

}<br />

return new File(dir, file);<br />

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

This program demonstrates one problem of relying on file extensions to determine file type.<br />

There are many other file extensions that indicate text files; for example, .c, .cc, .pl, .f, and<br />

many more. Furthermore, there are a lot of text files, especially on Macintoshes, that don't<br />

have any extension at all. This program completely ignores all those files.<br />

You do not necessarily have to write a new subclass for each different file filter. Example<br />

13.3 demonstrates a class that can be configured with different lists of filename extensions.<br />

Every file with an extension in the list passes the filter. Others don't.<br />

Example 13.3. ExtensionFilenameFilter<br />

package com.macfaq.io;<br />

import java.awt.*;<br />

import java.util.*;<br />

import java.io.*;<br />

311

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

Saved successfully!

Ooh no, something went wrong!