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.

Example 13.7. <strong>Java</strong>Chooser<br />

import java.io.*;<br />

import javax.swing.*;<br />

import javax.swing.filechooser.*;<br />

import com.macfaq.swing.filechooser.*;<br />

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

public class <strong>Java</strong>Chooser {<br />

}<br />

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

}<br />

JFileChooser fc = new JFileChooser();<br />

fc.addChoosableFileFilter(new <strong>Java</strong>Filter());<br />

int result = fc.showOpenDialog(new JFrame());<br />

if (result == JFileChooser.APPROVE_OPT<strong>IO</strong>N) {<br />

try {<br />

File f = fc.getSelectedFile();<br />

if (f != null) {<br />

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

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

fin.close();<br />

}<br />

}<br />

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

}<br />

System.exit(0);<br />

The JFileChooser class also a related accept() method:<br />

public boolean accept(File f)<br />

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

This passes the File object f through the file chooser's currently selected file filter. You'll<br />

have little reason to call this method directly, and it's unclear why it's even public.<br />

You do not need to construct a new subclass of FileFilter to create a new filter. Often it's<br />

more convenient to encapsulate some algorithm in a subclass than parameterize the algorithm<br />

in particular objects. For instance, Example 13.8 is an ExtensionFilter that extends<br />

FileFilter. It's similar to the ExtensionFilenameFilter of Example 13.3. However, this<br />

class also needs to store a description for each extension. Furthermore, the extensions are used<br />

one at a time, not all at once. This reflects the difference between JFileChooser and<br />

FileDialog.<br />

Example 13.8. ExtensionFilter<br />

package com.macfaq.swing.filechooser;<br />

import java.io.*;<br />

import javax.swing.filechooser.*;<br />

import javax.swing.*;<br />

321

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

Saved successfully!

Ooh no, something went wrong!