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.

13.2.2 Displaying File Choosers<br />

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

Although JFileChooser is a component, not a window, you usually want to display a modal<br />

dialog containing a JFileChooser component that asks the user to save or open a file. There<br />

are two methods that do this without requiring you to construct a dialog or frame explicitly:<br />

public int showOpenDialog(Component parent)<br />

public int showSaveDialog(Component parent)<br />

Although one method is for saving and one is for opening, you use them the same way. Both<br />

of these methods display a modal dialog. This dialog will block input to all of the<br />

application's windows and will block the current thread until the user either selects a file or<br />

cancels the dialog. If the user did choose a file, both these methods return<br />

JFileChooser.APPROVE_OPT<strong>IO</strong>N. If the user did not choose a file, both these methods return<br />

JFileChooser.CANCEL_OPT<strong>IO</strong>N.<br />

13.2.3 Getting the User's Selection<br />

If showOpenDialog() or showSaveDialog() returns JFileChooser.APPROVE_OPT<strong>IO</strong>N, the<br />

getSelectedFile() method returns a File object pointing to the file the user chose;<br />

otherwise, it returns null:<br />

public File getSelectedFile()<br />

If the file chooser allows multiple selections, getSelectedFiles()returns an array of all the<br />

files the user chose:<br />

public File[] getSelectedFiles()<br />

You can get a File object for the directory in which the selected file lives by calling<br />

getCurrentDirectory():<br />

public File getCurrentDirectory()<br />

Example 13.4 is a program that uses JFileChooser to ask the user to select a file and then<br />

prints the file's contents on System.out. This example is essentially the same as Example<br />

13.1, except that it uses JFileChooser instead of FileDialog.<br />

Example 13.4. JFileTyper<br />

import java.io.*;<br />

import javax.swing.*;<br />

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

public class JFileTyper {<br />

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

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

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

315

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

Saved successfully!

Ooh no, something went wrong!