Java Reference
In-Depth Information
int selection = fi leChooser.showOpenDialog(null);
if (selection == JFileChooser.APPROVE_OPTION)
//Specifi es action taken if fi le chosen.)
If a fi le has been selected, then method getSelectedFile returns the corresponding
File object. For example:
File fi le = fi leChooser.getSelectedFile();
For serial I/O of strings and the primitive types, we would then wrap either a
Scanner object (for input) or a PrintWriter object (for output) around the File object,
as we did in 4.1.
Scanner fi leIn = new Scanner(fi le);
PrintWriter fi leOut = new PrintWriter(fi le);
We can then make use of methods next, nextInt , etc. for input and methods print
and println for output.
Similarly, for serial I/O of objects, we would wrap either an ObjectInput-
Stream object plus FileInputStream object or an ObjectOutputStream object plus
FileOutputStream object around the File object.
ObjectInputStream fi leIn =
new ObjectInputStream(
new FileInputStream(fi le));
ObjectOutputStream fi leOut =
new ObjectOutputStream(
new FileOutputStream(fi le));
We can then make use of methods readObject and writeObject , as before. Of
course, since we are now dealing with a GUI, we need to implement ActionListener ,
in order to process our button selections.
This example is a simple application for reading a fi le of examination marks and
displaying the results of individual students, one at a time. The fi le holding results
will be a simple serial fi le, with each student's data held as three fi elds in the follow-
ing sequence: surname, fi rst name(s) and examination mark. We shall fi rstly allow
the user to navigate the computer's fi le system and select the desired fi le (employing
a JFileChooser object). Once a fi le has been selected, our program will open the fi le,
read the fi rst (logical) record and display its contents within the text fi elds of a panel
we have set up. This panel will also contain two buttons, one to allow the user to open
another fi le and the other to allow the user to move on to the next record in the fi le.
Search WWH ::

Custom Search