+ All Categories

chap10

Date post: 12-Dec-2015
Category:
Upload: ximi-vivar-de-la-cruz
View: 3 times
Download: 1 times
Share this document with a friend
Description:
Chap
41
File I/O Chapter 10
Transcript
Page 1: chap10

File I/O

Chapter 10

Page 2: chap10

Chapter Contents

Chapter Objectives

10.1 Introductory Example: Weather Data Analysis

10.2 Java/s I/O System: Readers, Writers, Streams

10.3 Exceptions

10.4 More About I/O Streams

10.5 Example: Scanning for a Virus

10.6 Example: Student Data Retrieval

10.7 Graphical/Internet Java: Student Data Retrieval GUI

Part of the Picture: Data Base Systems

Page 3: chap10

Chapter Objectives

Study Java's I/O with text and binary files Examine role of exceptions in I/O Observe use of files in GUI programs in

context of an information retrieval problem Learn about the role of files in database

management systems

Page 4: chap10

Need for File Access

Files saved for word processors, spreadsheet programs, etc.

Saved on secondary memory– hard disks, floppy disks, CD-ROMs, etc.

Requirements information stored in secondary memory– can be retrieved in the future– kept separate from other documents, programs, etc.

Page 5: chap10

Intro Example: Weather Data Analysis

Problem: large amounts of weather-related data is recorded and processed– year's worth of atmospheric pressure readings– taken every 15 minutes– stored in a text file pressure.dat

Weatherman needs minimum, maximum, and average of the data

Data must be read from file, statistics calculated, results written to a text output file

Page 6: chap10

Solution Overview

Note source code, Figure 10.1 Names of input and output files are given to the

program via the args parameter– input file is args[0]– output file is args[1]

Command to open the input fileBufferedReader in = new BufferedReader ( new FileReader (args[0]));

Reading text from input filevalueString = in.readLine();

Input file is a static object with

readLine() method

Input file is a static object with

readLine() method

Page 7: chap10

Solution Overview

Opening text output filePrintWriter out = new PrintWriter ( new BufferedWriter( new Filewriter (args[1])));

Writing text values to a file out.println ( . . . );

Closing the filesin.close(); out.close();

Page 8: chap10

Handling Exceptions

Many things can go wrong when dealing with files– requested input file does not exist– input file has invalid data– output file unavailable

When such an error occurs, the method in which the problem happened "throws an exception"– Java can "catch" the exception if it happens in a "try

block"– Note the try { … } block in the source code

Page 9: chap10

Handling Exceptions

A try block is followed by one or more "catch blocks"– Note the source code:catch (Exception anException) { Controller.fatal ( … ) ; }

This catch block will – determine the kind of exception – report the problem– terminate the program

Page 10: chap10

10.2 Java's I/O System: Readers, Writers, and Streams

All input and output in Java is accomplished by classes called streams

Input streams provide ways to move bytes of data from an input device to a program

Output streams move the data in the opposite direction

Executing Program

Output Stream

Input Stream

Page 11: chap10

Predefined Streams

System.in– InputStream object, usually for the keyboard

System.out– a buffered PrintStream object, usually the

screen or an active window

System.err– an unbuffered PrintStream object usually

associated with the screen or console window

Page 12: chap10

Wrapping Classes

InputStream class provides methods for reading bytes only– to read at a higher level we must "wrap" System.in with another class

Example: BufferedReader classBufferedReader myReader = new (BufferedReader ( new InputStreamReader( System.in));

Now we can send myReader either– the .read() message for a single char value or … – the .readLine() message for an entire line of text

Page 13: chap10

Using Readers and Writers

Reader and Writer classes provide support for char (16-bit Unicode) I/O

InputStream and OutputStream provide support for byte I/O

The Java language is still growing and "maturing"– extensions of Reader and Writer classes have yet to

be fully accepted– author of this text suggests: Use Reader or Writer

class whenever possible, use Stream class only when there is no Reader/Writer class that fits

Page 14: chap10

Using a Reader

Wrap FileReader in BufferedReader classBufferedReader inFile = new BufferedReader ( new FilReader (input_filename) );

Now the BufferedReader object (inFile) can be sent a .readLine() message

A BufferedReader is so named because it buffers the input– this improves program performance

Page 15: chap10

Using a Reader

How to know when all the data in a file has been read?– the readLine() method returns the value null

valueString = inFile.readLine():while (valueString != null) { … // process valueString valueString = inFile.readLine(); }

Also possible to check for other things such as an empty line with no textif (valueString.equals("")) continue;

Page 16: chap10

Sequence of steps for using text input

1. Build a BufferedReader by wrapping one around a FileReader

2. Use an input loop to read lines of text from the BufferedReader Convert those lines to numeric values if necessary

3. Close the BufferedReader

Using a Reader

Page 17: chap10

Using a Writer

When writing values to a text file, author suggests use a Writer class– increase FileWriter capabilities by wrapping it in BufferedWriter and PrintWriter classes

PrintWriter outFile = new PrintWriter(new BufferedWriter ( new FileWriter (file_name) ) );

Page 18: chap10

10.3 Exceptions

Easy for things to go wrong in a program– faulty logic– bad input from user, etc.

Java classifies all these as "exceptional occurrences"– provides Exception class– tells something abnormal occurred

Page 19: chap10

Try-Catch Blocks

To signal an abnormal occurrence– method can throw an exception– throw occurs inside a try block

try block followed by one or more catch blocksForm:try { … statement list … }

catch (Exception_Type1 variable_name1){ … }

catch (Exception_type2 variable_name2){ … }

finally { … }

Exception thrown here

Program searches catch blocks

looking for type match for exception

thrownWhen match found, that block of

statements executed

Page 20: chap10

Try-Catch Blocks

After catch block executed– execution continues in finally { } block or …– if no finally { }, continues to next statements

following catch { } If no matching exception type is found

– program terminates

If no exception thrown– catch blocks skipped– execution continues in finally { } or in

statements following catch block

Page 21: chap10

Exceptions become more specialized

Exception Hierarchy

D ataF orm atE xcep tion

E O F E xcep tion F ileN otF ou n d E xcep tion . . . In te rru p ted IO E xcep tion

IO E xcep tion . . . R u n tim eE xcep tion

E xcep tion

Most general class

Page 22: chap10

Try/Catch Strategy

Wrap all calls to methods that throw exceptions in single try block– followed by single catch block .. or …– followed by sequence of catch blocks, one for each

type of exception

Wrap each call to a method that throws an exception in its own try block– a catch block exists for each particular exception

thrown

Page 23: chap10

Throwing Exceptions

Method that throws an exception must explicitly state this in its heading

public void read(BufferedReader aReader) throws EOFException

Now calling method must invoke this method using try-catch blocks to handle the potential exception

Page 24: chap10

10.4 More About I/O Streams

Data can be stored in a file as text or in binary format– same format used to store values in memory– takes less space to store an integer in binary format

than in text format

Java Stream classes provide byte level I/O– FileOutputStream – FileInputStream– Also BufferedOutputStream and

BufferedInputStream

Page 25: chap10

Writing Primitive types

Java provides DataOutputStream and DataInputStream classes

Note methods provided, Table 10.1– note number of bytes used to store the data

Consider Data Stream Demonstration, Figure 10.3 in text – note the features …– wrapping of Stream I/O classes– use of try-catch blocks– specific methods used to write, then read – sample run

Why does contents of numbers.dat

appear to be gibberish?

Why does contents of numbers.dat

appear to be gibberish?

Page 26: chap10

Writing Sequence of Values

Consider a group of values of different types that are written to a file– they must be read in the same order that they were

written

Possible to create a class– that group of values is the private data of the class– specific methods are provided for an object of the

class to write/read those values to/from a file– the read and write methods receive the file handles

as parameters

Page 27: chap10

10.5 Example: Scanning for a Virus

What is a virus?– software that hides itself within other executable

programs– that executable program is the "host" for the virus– the virus program tries to "infect" other programs– the virus can cause problems that range from

annoying to malicious

A virus that prints an annoying message stores that string value within itself– we will write a program that searches through a file

to find that text, or signature

Page 28: chap10

Virus-Detection Algorithm

1. Repeat the following:a) read a line from a file

b) if no line read due to EOF, terminate

c) otherwise scan the line for specified string of text

d) if that text found, stop reading from file

2. Display message whether or not target string was found – signifying virus found/not found

Note source code, Figure 10.4

Page 29: chap10

Simulated Virus Scanning

Note use of command line arguments– first argument is the name of the file to be read– second argument is the target string or virus

signature

Observe other features studied in this chapter– use of try/catch– wrapping of classes for file read

Page 30: chap10

10.6 Example: Retrieving Student Information

Problem: Information Retrieval

Records of information about students consist of– studentID, a 9 digit integer– first name, last name as strings– studentYear as a string– credits and GPA as reals

We seek a program which will – read a sequence of students from students.txt– prompt for studentID, read from keyboard– search for match, display if found

Page 31: chap10

Objects

Objects Type Kind Name

Individual Student Student varying

Number of students

int varying numberOfStudents

Sequence of students

StudentSequence varying students

Name of input file String constant args[0]

A student ID number

int varying studentID

Position of the student

int varying position

Page 32: chap10

Student Class

Operations needed include– initialize itself with default values– initialize itself with explicitly supplied values– read its attributes from a BufferedReader & store

them in itself– convert itself to a String (for output)– access each of its attributes– mutate any of its attributes

Note methods provided for these capabilities in source code of Figure 10.5

Page 33: chap10

Program Algorithm

1. Build students as a StudentSequencea) initialized from an input file

b) name of file received in args[0]

2. Repeatedly do the following:a) prompt for and read studentID

b) search students for target studentID, return its position

c) if search successful display student at positionotherwise display error message

Page 34: chap10

Class StudentSequence

Note source code, Figure 10.6 Reads numberOfStudents as first value in

the file Constructor declares myStudents, an array of Student

Use numberOfStudents as limiting value in for loop – stores incoming values in myStudents array

Provides linear search method, find()

Page 35: chap10

Student Information Retrieval

Note source code, Figure 10.7 Program declares students, object of type StudentSequence– constructor loads values from file

Forever loop used to – prompt for, receive as input student id– call .find method to determine position of that

student in the array– print results (found or not)

Page 36: chap10

10.7 Graphical/Internet Java:Student Data Retrieval GUI

Implement student data retrieval problem internet GUI context

Much of work already done can be reused Behavior GUIStudentRetriever

Enter Student ID : 111223333

Credits GPA

Bill Board

Freshman 16.0 3.15Alternatively, a "not

found" message would appear here

Bottom portion not visible until id entered and processed

Page 37: chap10

Implementation

Methods for GUIStudentRetreiver– constructor– action handler– enter initial state– enter found an ID state– enter not found state

Attributes– labels– entry fields– panes for panels

Page 38: chap10

Event-Handler Method

public void actionPerformed(ActionEvent event)

{ String idString = myIdField.getText();

if (idString.equals("")) enterInitialState();

else{ int id = Integer.parseInt(idString);

int position = myStudents.find(id);

if (position >= 0)

enterGoodIDState(myStudents.getStudent(position));

else

enterErrorState("No student found with that ID");

}

}Note source code, Figure 10.8Note source code, Figure 10.8

Page 39: chap10

Part of the Picture:Database Systems

Businesses must make decisions

Based on data– accuracy and detail help make better decisions– large data sets stored on computers

Data sets maintained by Database Management Systems (DBMS)

Page 40: chap10

DBMS Facilities

High level views of the data Access routines

– query language Support for large databases

– as large as 1000 gigabytes (one terabyte) Security

– data is sensitive or proprietary Data sharing

– protect data when more than one person wishes to access/ modify same piece of data

Data integrity

Page 41: chap10

Relational Model

Database viewed as a set of tables, called relations– one row for each entry– column for each attribute or field of the database

SQL, "Structured Query Language"– provides commands for manipulate data

ExampleSELECT * FROM Employee WHERE Rate = 10.5

Retrieve All recordsName of Relation Condition


Recommended