Chapter 11 Text file I/O and simple GUI dialogues Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2 http://www.ii.uib.no/~khalid/jac/ Permission is hereby granted to use these lecture slides in conjunction with the book. Modified: 14/11/08 Java Actually 11: Text file I/O and simple GUI dialogues 11-1/24 Overview Text File I/O File handling Data records Text files Simple GUI dialogue design: javax.swing.joptionpane Message dialogs presenting information to the user Input dialogs reading data from the user Confirmation dialogs getting confirmation from the user Java Actually 11: Text file I/O and simple GUI dialogues 11-2/24
Input and Output Input: Data a program reads. Input comes from a source which produces the data. For example keyboard, a file Output: Data a program writes. Output is written to a destination that can receive the data. For example terminal window, a file A data file offers permanent storage of data from a program on some external media. Java Actually 11: Text file I/O and simple GUI dialogues 11-3/24 File handling A file denotes a specific storage area on some external media, for example hard disk, where information is stored. Data in filer is stored as a sequence of bytes. Binary file: Data is interpreted as a sequence of bytes. Text file: Data is interpreted as a sequence of character, where a character can be represented by one or more bytes. Java Actually 11: Text file I/O and simple GUI dialogues 11-4/24
Default size of primitive data types Primitive data types boolean 1 char 2 int 4 long 8 float 4 double 8 Size in bytes Java Actually 11: Text file I/O and simple GUI dialogues 11-5/24 File path A file path identifies a file in the file system: String datafilename = "employees.dat"; // File path identifies // the file. String filepath1 = "company\\employees.dat"; // Windows String filepath2 = "company/employees.dat"; // Unix String filename = "company" + File.separator + "employees.dat"; Java Actually 11: Text file I/O and simple GUI dialogues 11-6/24
Data Records Problem: Store information about employees on a file. String firstname; String lastname; double hourlyrate; Gender gender; A record consists of one or more data fields. A field usually contains a primitive value, but it can also be a string. field 1 field 2 field 3 field 4 Ole Olsen 30.00 MALE record field 1 field 2 field 3 field 4 Bill Bailey 40.00 MALE See Program 10.1: Classes Employee and PersonnelRegister. Java Actually 11: Text file I/O and simple GUI dialogues 11-7/24 Text Files A text file contains lines of text. A text line consists of a sequence of characters terminated by a line terminator string. Methods in Java ensure that the line terminator string is interpreted correctly. Procedure for handling files: 1. Open the file. 2. Choose appropriate class to convert values between the program and the file. 3. Read from or write to the file. 4. Close the file. Java Actually 11: Text file I/O and simple GUI dialogues 11-8/24
It's now or never Flaming Star Suspious Minds Angel Crying in the Chapel If I can dream Fever CC Rider Little Sister Are you lonesome tonight? Devil in desguise Writing to a text file print(boolean b) print(char c) print(char[] carray) print(double d) print(float f) print(int i) print(long l) print(object obj) print(string str) println() println(...) printf(...)... Object of class PrintWriter Object of class FileWriter values char bytes Step 2 Step 1 text file FileWriter textfilewriter = new FileWriter(textFileName); // Step 1 PrintWriter textwriter = new PrintWriter(textFileWriter); // Step 2 Java Actually 11: Text file I/O and simple GUI dialogues 11-9/24 See Program 10.1 and Program 10.2. Writing to a text file (cont.) 1. Create a FileWriter object to open the file for writing: FileWriter textfilewriter = new FileWriter(dataFileName); // (5) 2. Create a PrintWriter object that is connected to the FileWriter from step 1: PrintWriter textwriter = new PrintWriter(textFileWriter); // (6) 3. Write text representations of values using the print methods of the PrintWriter class. textwriter.printf( "%s" + FIELD_TERMINATOR + "%s" + FIELD_TERMINATOR + "%.2f" + FIELD_TERMINATOR + "%s%n", employee.firstname, employee.lastname, employee.hourlyrate, employee.gender); 4. Finish by closing the file: textwriter.close(); // (9) Java Actually 11: Text file I/O and simple GUI dialogues 11-10/24
It's now or never Flaming Star Suspious Minds Angel Crying in the Chapel If I can dream Fever CC Rider Little Sister Are you lonesome tonight? Devil in desguise Basic Exception Handling An exception signals that an error or an unexpected situation has occurred during execution. Normal execution is suspended and if no actions is taken by the program, execution is aborted. Exception handling is based on throw-and-catch principal. If a checked exception can be thrown by a method, the compiler reports an error if the method does not explicitly deal with the exception. A method must either catch the exception, or throw it again. A throws clause in the method header specifies checked exceptions that a method can throw. Employee reademployeedata(bufferedreader textreader) throws IOException { // (17)... String record = textreader.readline(); // (18)... Java Actually 11: Text file I/O and simple GUI dialogues 11-11/24 Reading from a text file Object of class FileReader Object of class BufferedReader String readline() bytes char text file Step 1 Step 2 text line FileReader textfilereader = new FileReader(textFileName); // Step 1 BufferedReader textreader = new BufferedReader(textFileReader); // Step 2 Java Actually 11: Text file I/O and simple GUI dialogues 11-12/24
See Program 10.1 and Program 10.2. Reading from a text file 1. Create a FileReader object to open the file for reading: FileReader textfilereader = new FileReader(dataFileName); // (12) 2. Create a BufferedReader object that is connected to the FileReader from step 1: BufferedReader textreader = new BufferedReader(textFileReader);// (13) 3. Read one text line at a time using the readline() method of the BufferedReader class: String record = textreader.readline(); // (18) Characters in each field can be extracted (see the figure below): int fieldterminatorindex1 = record.indexof(field_terminator); // (19) String firstname = record.substring(0, fieldterminatorindex1); // (20) Characters must be converted to primitive values (see the figure below): String doublestr = record.substring(fieldterminatorindex2 + 1, fieldterminatorindex3); double hourlyrate = Double.parseDouble(doubleStr); // (21) String genderstr = record.substring(fieldterminatorindex3 + 1); Java Actually 11: Text file I/O and simple GUI dialogues 11-13/24 Gender gender; if (genderstr.equals(gender.male.tostring())) { // (22) gender = Gender.MALE; else { gender = Gender.FEMALE; 4. Close the file: textreader.close(); // (9) Java Actually 11: Text file I/O and simple GUI dialogues 11-14/24
Reading records and converting fields to appropriate values Step 1: Find the index of the field terminator characters fieldterminatorindex1 fieldterminatorindex2 fieldterminatorindex3 index Text line 0 3 9 15 O l e, O l s e n, 3 0. 0 0, M A L E \n Step 2: Extract substrings field 1 field 2 field 3 field 4 "Ole" "Olsen" "30.00" "MALE" Step 3: Convert substrings to floating-point to a Gender value 30.0 Gender.MALE Java Actually 11: Text file I/O and simple GUI dialogues 11-15/24 Simple Dialogue Design with the class JOptionPane The class JOptionPane provides dialog boxes that can be used to: present information to the user read input from the user confirm information from the user The class defines 3 static methods: showtypedialog(), where Type can be replaced with Message, Input or Confirm, depending on the kind of dialog box. All dialog boxes are modal. GUI-based programs must be terminated by the call System.exit(0) in the source code. Tables 10.2 to 10.6 provide API information about using the class JOptionPane. Java Actually 11: Text file I/O and simple GUI dialogues 11-16/24
Presenting data to the user Such a dialog box usually displays a message to the user and an OK button that the user can click to dismiss the dialog box after having read the message. The showmessagedialog() can be used for this purpose. Using the method showmessagedialog()(program 10.3) JOptionPane.showMessageDialog( // (1) null, "How ya'doin!"); (a) JOptionPane.showMessageDialog( // (2) null, "You have hit the jackpot!", "Important Message", JOptionPane.WARNING_MESSAGE); (b) Java Actually 11: Text file I/O and simple GUI dialogues 11-17/24 Reading input from the user This type of dialog box presents a text field that user can type in, and 2 buttons (OK and CANCEL) for submitting the data or cancelling the dialog box. The showinputdialog() can be used for this purpose. The method returns the contents of the text field as a string that must be explicitly converted to types of values, as required by the program. Java Actually 11: Text file I/O and simple GUI dialogues 11-18/24
Using the method showinputdialog()(program 10.4) JOptionPane.showInputDialog( // (1) "Name:" ); (a) JOptionPane.showInputDialog( // (2) null, "Zipcode:" ); (b) JOptionPane.showInputDialog( // (4) null, "City:", "Input data", JOptionPane.PLAIN_MESSAGE); (c) Java Actually 11: Text file I/O and simple GUI dialogues 11-19/24 Confirming information from the user Such a dialog box usually consists of a question about some fact that the user must confirm. In addition the dialog box has 2 buttons (YES and NO) to answer the question. The showconfirmdialog() can be used for this purpose. The return value can be interpreted as shown in Table 10.5. The method can also take a parameter that specifies the option type (Table 10.6). Java Actually 11: Text file I/O and simple GUI dialogues 11-20/24
Using the method showconfirmdialog()(program 10.5) JOptionPane.showConfirmDialog( // (1) null, "Are you getting married?"); (a) JOptionPane.showConfirmDialog( // (2) null, "We understand each other, right?", "Confirmation 2", JOptionPane.YES_NO_OPTION ); (b) JOptionPane.showConfirmDialog( // (3) null, "Java is fun, right?", "Confirmation 3", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); (c) Java Actually 11: Text file I/O and simple GUI dialogues 11-21/24 Support for Simple GUI dialogue See the GUIDialog.java (Program E.3). Static methods in class GUIDialog Description int requestint(object prompt) Read an int value double requestdouble(object prompt) Read an double value String requeststring(object prompt) Read an non-empty string void prompt(object message) Write a message int confirminfo(object information) Confirm information Java Actually 11: Text file I/O and simple GUI dialogues 11-22/24
Example: Using the class GUIDialog // Using GUIDialog class public class GUIDialogDemo { public static void main(string[] args) { GUIDialog.prompt( // (1) "Program finds the largest number in a sequence of numbers.\n" + "A negative number signals end of the sequence."); int maxvalue = 0; while (true) { int n = GUIDialog.requestInt("Enter an integer: "); // (2) if (n < 0) { break; if (n > maxvalue) { maxvalue = n; GUIDialog.prompt("Largest number: " + maxvalue); // (3) System.exit(0); Java Actually 11: Text file I/O and simple GUI dialogues 11-23/24 Example: Dialogue Boxes (a) (b) (c) (d) (e) (f) (g) Java Actually 11: Text file I/O and simple GUI dialogues 11-24/24