The java.awt.FileDialog
class is a subclass of java.awt.Dialog
used for choosing a file to open or save.
This class uses the host platform's standard open and save file
dialogs. You won't add components to a FileDialog
, or
handle user interaction. You'll just retrieve
the result which will be the name and directory of a file. Since an
applet can't rely on having access to the file system, FileDialog
s are primarily useful in applications.
There are three steps to using a FileDialog:
FileDialog
FileDialog
visible.
You create a FileDialog
with the constructor
public FileDialog(Frame parent, String title, int mode)
The Frame
is the parent of this file dialog. This will
normally be the main window of the application
or the frontmost window of the application.
The title
argument is simply
the title for the FileDialog
, normally something like
"Please choose the file to open:" mode
is one of the
two mnemonic constants FileDialog.LOAD
or FileDialog.SAVE
. Use FileDialog.LOAD
if you
want the user to choose a file to open. Use FileDialog.SAVE
if you want the user to choose a file to
save the data into. A typical use of this might look like
FileDialog fd = new FileDialog(new Frame(),
"Please choose the file to open:", FileDialog.LOAD);
Finally make the FileDialog
visible the same way you
make any other window visible. Just pass true
to the
FileDialog
's setVisible()
method.
fd.setVisible(true);
At this point the operating system takes over and handles user
interaction until the user either chooses a file or cancels. Your
program stops here and waits for the user to choose a file. When
the user does choose a file, the file dialog disappears from the
screen and your program resumes. You then find out what file the
user chose by using the file dialog's getDirectory()
and getFile()
methods. Use these two strings to create
a new File
object. In short,
FileDialog fd = new FileDialog(new Frame(),
"Please choose a file:", FileDialog.LOAD);
fd.show();
if (fd.getFile() != null) {
File f = new File(fd.getDirectory(), fd.getFile());
}
If the user cancels the save, both getDirectory()
and getFile()
return null. Be sure to check for
this!