• No results found

Text file I/O and simple GUI dialogues

N/A
N/A
Protected

Academic year: 2021

Share "Text file I/O and simple GUI dialogues"

Copied!
12
0
0

Loading.... (view fulltext now)

Full text

(1)

Java Actually 11: Text file I/O and simple GUI dialogues 11-1/24

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

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

(2)

Java Actually 11: Text file I/O and simple GUI dialogues 11-3/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.

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.

(3)

Java Actually 11: Text file I/O and simple GUI dialogues 11-5/24

Default size of primitive data types

Primitive data types Size in bytes boolean 1 char 2 int 4 long 8 float 4 double 8

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

(4)

Java Actually 11: Text file I/O and simple GUI dialogues 11-7/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.

• See Program 10.1: Classes Employee and PersonnelRegister. MALE 30.00 Olsen Ole field1 record

field2 field3 field4

MALE 40.00

Bailey Bill

field1 field2 field3 field4

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.

(5)

Java Actually 11: Text file I/O and simple GUI dialogues 11-9/24

Writing to a text file

FileWriter textFileWriter = new FileWriter(textFileName); // Step 1 PrintWriter textWriter = new PrintWriter(textFileWriter); // Step 2

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 Object of class PrintWriter Object of class FileWriter text file Step 2 Step 1 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(...) ...

values char bytes

Writing to a text file (cont.)

• See Program 10.1 and Program 10.2.

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:

(6)

Java Actually 11: Text file I/O and simple GUI dialogues 11-11/24

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) ...

}

Reading from a text file

FileReader textFileReader = new FileReader(textFileName); // Step 1 BufferedReader textReader = new BufferedReader(textFileReader); // Step 2

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

Object of class

BufferedReader

Object of class

FileReader

text file Step 1 Step 2

String readLine()

(7)

Java Actually 11: Text file I/O and simple GUI dialogues 11-13/24

Reading from a text file

• See Program 10.1 and Program 10.2.

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);

Gender gender; if (genderStr.equals(Gender.MALE.toString())) { // (22) gender = Gender.MALE; } else { gender = Gender.FEMALE; }

4. Close the file:

(8)

Java Actually 11: Text file I/O and simple GUI dialogues 11-15/24

Reading records and converting fields to appropriate values

O l e , O l s e n , 3 0 . 0 0 , M A L E \n

Text line index

Step 2: Extract substrings

Step 1: Find the index of the field terminator characters

Step 3: Convert substrings to floating-point to a Gender value

0 3 9 15

fieldTerminatorIndex1 fieldTerminatorIndex2 fieldTerminatorIndex3

Gender.MALE "MALE" 30.0 "30.00" "Olsen" "Ole"

field1 field2 field3 field4

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.

(9)

Java Actually 11: Text file I/O and simple GUI dialogues 11-17/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)

(a) JOptionPane.showMessageDialog( // (1) null, "How ya'doin!"); (b) JOptionPane.showMessageDialog( // (2) null,

"You have hit the jackpot!", "Important Message",

JOptionPane.WARNING_MESSAGE);

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.

(10)

Java Actually 11: Text file I/O and simple GUI dialogues 11-19/24

Using the method

showInputDialog()

(Program 10.4)

(c)

JOptionPane.showInputDialog( // (4) null, "City:",

"Input data", JOptionPane.PLAIN_MESSAGE);

(a) (b) JOptionPane.showInputDialog( // (1) "Name:" ); JOptionPane.showInputDialog( // (2) null, "Zipcode:" );

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.

(11)

Java Actually 11: Text file I/O and simple GUI dialogues 11-21/24

Using the method

showConfirmDialog()

(Program 10.5)

(c)

JOptionPane.showConfirmDialog( // (3) null,

"Java is fun, right?", "Confirmation 3", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); (a) (b) JOptionPane.showConfirmDialog( // (1) null,

"Are you getting married?");

JOptionPane.showConfirmDialog( // (2) null,

"We understand each other, right?", "Confirmation 2",

JOptionPane.YES_NO_OPTION );

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

(12)

Java Actually 11: Text file I/O and simple GUI dialogues 11-23/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);

} }

Example: Dialogue Boxes

(a)

References

Related documents

• Follow up with your employer each reporting period to ensure your hours are reported on a regular basis?. • Discuss your progress with

The purpose of this study was to evaluate the diagnostic utility of real-time elastography (RTE) in differentiat- ing between reactive and metastatic cervical lymph nodes (LN)

In this PhD thesis new organic NIR materials (both π-conjugated polymers and small molecules) based on α,β-unsubstituted meso-positioning thienyl BODIPY have been

Spain’s Podemos, Greece’s Syriza, France’s Parti de Gauche and Portugal’s Left Bloc and Communist Party, together with like-minded parties across Europe have been inspired in

Any balance remaining in the Participant's Health Flexible Spending Account or Dependent Care Flexible Spending Account as of the end of the time for claims reimbursement

• Dum Dums • Chewy Pops • Saf-T-Pops • Candy Canes • Chewy Canes • Circus Peanuts • Shrek Ogreheads SURF SWEETS • Gummy Worms • Gummy Swirls • Gummy Bears • Fruity Bears

An analysis of the economic contribution of the software industry examined the effect of software activity on the Lebanese economy by measuring it in terms of output and value

Trying to fill the gap in the literature, this study proposed an integrated BSC–FAHP model for evaluat- ing and selecting suppliers by considering the characteristics of