FIGURE 13.1: The file chooser dialog box.
be pressed in order to select a file. A cancel button also appears. The method returns
an integer that is either JFileChooser.APPROVE OPTION , JFileChooser.CANEL OPTION ,or
JFileChooser.ERROR OPTION . Next, we can use the getSelectedFile method to get the
file that is selected by the user. Here is an example piece of code that selects a file using
the file chooser dialog.
JFileChooser fileChooser = new JFileChooser () ;
if ( fileChooser . showDialog ( . . . , "Open" ) == JFileChooser .APPROVEOPTION)
File newFile = fileChooser . getSelectedFile() ;
Note that, for now, we have left the parent window parameter unspecified because we
do not know its value.
13.2.2 Reading from Text Files
Our next job is to open the text file and read the information from it. Reading from a
text file is similar to reading from the keyboard. A Scanner object needs to be created and
different methods, such as nextInt , next ,and nextLine , can be called on it. When creating
the Scanner object, a file object needs to be specified as input (instead of Systems.in for
keyboard input). Here is an example code.
Scanner fileHandler = new Scanner(newFile) ;
String nextLine = fineHandler . nextLine () ;
Note that in our case the file chooser returns an object of type File .Ifwewanttofind
the file name (as a string) that corresponds to the object, we can write newFile.getPath() .
This will return the file name together with the directory path to the file. Alternatively, if
we want to open a file with a given name, we can use the following syntax.
Scanner keyboard = new Scanner(System. in) ;