Java Reference
In-Depth Information
File inputFile = new File("input.txt");
describes the file
input.txt
in the current directory. The
File
class has
methods to delete or rename the file. The file does not actually have to existȌyou
may want to pass the
File
object to an output stream or writer so that the file can
be created. The
exists
method returns
true
if the file already exists.
A
File
object describes a file or directory.
You cannot directly use a
File
object for reading or writing. You still need to
construct a file reader or writer from the
File
object. Simply pass the
File
object in the constructor.
FileReader in = new FileReader(inputFile);
The
JFileChooser
class has many options to fine-tune the display of the dialog
box, but in its most basic form it is quite simple: Construct a file chooser object;
then call the
showOpenDialog
or
showSaveDialog
method. Both methods
show the same dialog box, but the button for selecting a file is labeled ȒOpenȓ or
ȒSaveȓ, depending on which method you call.
You can pass a
File
object to the constructor of a file reader, writer, or
stream.
For better placement of the dialog box on the screen, you can specify the user
interface component over which to pop up the dialog box. If you don't care where
the dialog box pops up, you can simply pass
null
. These methods return either
JFileChooser.APPROVE_OPTION
, if the user has chosen a file, or
JFileChooser.CANCEL_OPTION
, if the user canceled the selection. If a file
was chosen, then you call the
getSelectedFile
method to obtain a
File
object that describes the file. Here is a complete example:
JFileChooser chooser = new JFileChooser();
FileReader in = null;
if (chooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();