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.

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

don't want to. File dialogs are modal. While the file dialog is shown, input to the parent frame<br />

is blocked, as with the parent frame of any modal dialog. The title argument is the prompt<br />

string for the file dialog, normally something like "Please choose the file to open:". The mode<br />

argument is one of the two mnemonic constants FileDialog.LOAD or FileDialog.SAVE:<br />

public static final int LOAD = 0;<br />

public static final int SAVE = 1;<br />

Use FileDialog.LOAD if you want the user to choose a file to open. Use FileDialog.SAVE if<br />

you want the user to choose a file to save the data into. A typical use of this constructor might<br />

look like this:<br />

FileDialog fd = new FileDialog(new Frame("Dummy frame"),<br />

"Please choose the file to open:", FileDialog.LOAD);<br />

To specify that the file dialog should appear with a particular directory opened or a particular<br />

file in that directory selected, you can invoke the setDirectory() and setFile() methods:<br />

public synchronized void setDirectory(String directory)<br />

public synchronized void setFile(String file)<br />

For example:<br />

fd.setDirectory("/etc");<br />

fd.setFile("passwd");<br />

You make the file dialog visible by invoking the file dialog's show() method, just like any<br />

other window:<br />

fd.show();<br />

As soon as the file dialog becomes visible, the calling thread stops and waits for the user to<br />

choose a file. The operating system takes over and handles user interaction until the user<br />

chooses a file or presses the Cancel button. At this point, the file dialog disappears from the<br />

screen, and normal program execution resumes.<br />

Once the dialog has been dismissed, you can find out which file the user chose by using the<br />

file dialog's getDirectory() and getFile() methods:<br />

public String getFile()<br />

public String getDirectory()<br />

For example:<br />

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

FileDialog.LOAD);<br />

fd.setVisible(true);<br />

File f = new File(fd.getDirectory(), fd.getFile());<br />

If the user cancels the file dialog without selecting a file, getFile() and getDirectory()<br />

return null. You should be ready to handle this, or you'll bump into a<br />

NullPointerException in short order.<br />

308

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

Saved successfully!

Ooh no, something went wrong!