Text file I/O and simple GUI dialogues



Similar documents
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Object-Oriented Programming in Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CS 106 Introduction to Computer Science I

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Introduction to Java

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Creating a Simple, Multithreaded Chat System with Java

Event-Driven Programming

13 File Output and Input

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

WRITING DATA TO A BINARY FILE

Stream Classes and File I/O

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

public static void main(string[] args) { System.out.println("hello, world"); } }

CS506 Web Design and Development Solved Online Quiz No. 01

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

D06 PROGRAMMING with JAVA

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chapter 2 Introduction to Java programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

INPUT AND OUTPUT STREAMS

Files and input/output streams

Sample CSE8A midterm Multiple Choice (circle one)

Explain the relationship between a class and an object. Which is general and which is specific?

Introduction to Java Applets (Deitel chapter 3)

JAVA - FILES AND I/O

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Lecture 5: Java Fundamentals III

Continuous Integration Part 2

Pemrograman Dasar. Basic Elements Of Java

Using Files as Input/Output in Java 5.0 Applications

CS 111 Classes I 1. Software Organization View to this point:

What is an I/O Stream?

Lesson: All About Sockets

PIC 10A. Lecture 7: Graphics II and intro to the if statement

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Chapter 2 Elementary Programming

1001ICT Introduction To Programming Lecture Notes

Quick Introduction to Java

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

A Brief Introduction to MySQL

AP Computer Science File Input with Scanner

Introduction to Java. CS 3: Computer Programming in Java

Object Oriented Software Design

Chapter 2: Elements of Java

AP Computer Science Java Subset

Sources: On the Web: Slides will be available on:

Example of a Java program

ECE 122. Engineering Problem Solving with Java

Programming in Java

J a v a Quiz (Unit 3, Test 0 Practice)

Reading Input From A File

Division of Informatics, University of Edinburgh

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

CS 1302 Ch 19, Binary I/O

Comp 248 Introduction to Programming

Part I. Multiple Choice Questions (2 points each):

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Course Intro Instructor Intro Java Intro, Continued

How to Install Java onto your system

Computer Programming I

CS 121 Intro to Programming:Java - Lecture 11 Announcements

An Overview of Java. overview-1

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Building a Multi-Threaded Web Server

Appendix K Introduction to Microsoft Visual C++ 6.0

Java Programming Fundamentals

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

JUnit - A Whole Lot of Testing Going On

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Programming Languages CIS 443

Crash Course in Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Mail User Agent Project

Chapter 3. Input and output. 3.1 The System class

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Programmierpraktikum

Week 1: Review of Java Programming Basics

Application Development with TCP/IP. Brian S. Mitchell Drexel University

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Unit 6. Loop statements

Install Java Development Kit (JDK) 1.8

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

JAVA Program For Processing SMS Messages

Chapter 1. Introduction to Computers, Programs, and Java

Transcription:

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