You are on page 1of 31

SSD3: Object-Oriented Programming and

Design

Object-Oriented Programme 1
Unit 3. Advanced Class Implementation
 3.1 Input and Output Programming
 3.2 Graphical User Interface
 3.3 Toward Commercial Use

 Assessments
 Exam 3

Object-Oriented Programme 2
3.1 Input and Output Programming
 Contents
 3.1.1 File I/O
 3.1.2 Using File I/O in the Library System

 Assessments
 PracticalQuiz 9
 Exercise 6

Object-Oriented Programme 3
3.1.1 File I/O
 Declaring and Initializing File I/O Objects
 Using File I/O Objects
 Closing Files
 Sample File I/O Program

Object-Oriented Programme 4
Declaring and Initializing File I/O Objects
 we have learnt console I/O.
 Classes needing console I/O began with the
following declarations:
/* Standard input stream */
private static BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));

/* Standard output stream */
private static PrintWriter stdOut =
new PrintWriter(System.out, true);

/* Standard error stream */
private static PrintWriter stdErr =
new PrintWriter(System.err, true);

Object-Oriented Programme 5
note
 BufferedReader and PrintWriter 包装类
simply wrap the more primitive console I/O
objects (初级 io 类) System.in,
System.out, and System.err
providing a more refined and convenient
interface.
 They can be used to wrap other I/O objects,
including those used for file I/O.

Object-Oriented Programme 6
file I/O classes
 so, classes needing file I/O will use the
following declarations:
BufferedReader fileIn =
new BufferedReader(new FileReader(filename));

PrintWriter fileOut =
new PrintWriter(new FileWriter(filename));

PrintWriter fileAppend =
new PrintWriter(new FileWriter(filename, true);

Object-Oriented Programme 7
note
 The argument filename used in the declarations is
simply a String indicating the name of the file to be
opened.
 What the FileReader constructor do?
 creates an object
 opens the specified file for reading.
 It provides a mechanism for reading data from the
file.

Object-Oriented Programme 8
note
 The FileWriter constructor
 makes it possible to write data to the specified
file. 打开文件准备写入
 When the one-argument FileWriter constructor
opens a file, it erases the contents of the file.
 Obviously, this is not appropriate in some situations.
 When data needs to be appended to a file, the two-argument
FileWriter constructor should be used:
 if the second argument is true, the contents of the file are preserved
when the file is opened.
 If the second argument is false, the contents are erased. 小心使用!

 When a file is opened for writing and the specified
file does not exist
 a new empty file is created by the host system.

Object-Oriented Programme 9
Using File I/O Objects
 Declaring file I/O objects is very similar to declaring
console I/O objects. 其实他们都是处理数据流,只
是来源与目的地不同
 FileReader and FileWriter objects
 similarly wrapped by BufferedReader and
PrintWriter
 File I/O and console I/O objects share many
methods. (See Java API document)

Object-Oriented Programme 10
Code comparison (file I/O vs. console I/O )-1
 As
a consequence, the code for file I/O looks very
much like the code for console I/O.
// reading from a file
int value = Integer.parseInt(fileIn.readLine());

// reading from the console
int value = Integer.parseInt(stdIn.readLine());

Object-Oriented Programme 11
BufferedReader.readLine()
 method BufferedReader.readLine()
 used to read the contents of a file
 return null when it reaches the end of the file.
 The following loop, which reads all the lines in a
file, takes advantage of this fact:
String line = fileIn.readLine();

while (line != null) {

// process line
line = fileIn.readLine();
}

Object-Oriented Programme 12
Code comparison (file I/O vs. console I/O )-2
 writing to a file v.s. writing to the console

// writing to a file
fileOut.println(5);

// writing to the console
stdOut.println(5);

Object-Oriented Programme 13
extra attention when dealing with file I/O
 Whilethe initialization of console I/O objects
generally succeeds 控制台 io 出错的可能性极小
 The BufferedReader, InputStreamReader, and PrintWriter
constructors presented do not throw any exceptions
 initializing file I/O objects can fail:
 The FileReader constructor that takes a filename as argument can
throw a FileNotFoundException.
 This should be expected, as it is certainly reasonable to think that the
string given to this constructor may be the name of a file that does not
exist.
 Note that FileNotFoundException is a direct subclass of IOException.
 The FileWriter constructors that take a filename as argument also
can throw an IOException.
 In addition, the method readLine() in the class BufferedReader
throws an IOException if there is an error during reading.

Object-Oriented Programme 14
Closing Files
 Maintaining open files requires scarce system resources,
 So, Files that are no longer in use should be closed.
 Who do the job to close files?
 This must be done explicitly by the programmer.
BufferedReader fileIn =
new BufferedReader(new FileReader(filename));
PrintWriter fileOut =
new PrintWriter(new FileWriter(filename));
...
fileIn.close();
fileOut.close();
 close() in the classes BufferedReader and PrintWriter throw
an IOException if there is an error during closing the files.
Object-Oriented Programme 15
Sample File I/O Program
 Sample code of file I/O(CopyFile.java)
 It first prompts the user for two file names, the name of an
input file and the name of an output file, and then copies the
contents of the input file to the output file.
 In lines 34 and 40, the input and output files are opened.
 The code from line 43 to line 48 reads a line from the
input file and writes the line just read to the output file.
When the end of the file is reached, the value of the
variable line becomes null, and control exits the while-
loop.
 In lines 50 and 51, the files are closed.

Object-Oriented Programme 16
3.1.2 Using File I/O in the Library System
 Reading Data from a File
 Writing Data to a File
 Complete Library System

Object-Oriented Programme 17
version of the library system with file I/O
 New Requirement:
 The catalog will be stored in a data file
 the library system will load the catalog from that
file.
 The user will be able to save the borrower data
to a file in one of three formats: Plain text, HTML
and XML.

Object-Oriented Programme 18
Reading Data from a File
 Recall that the library system contains two kinds of
catalog items: books and recordings.
 Every line in catalog.dat stores exactly one catalog
item.

Object-Oriented Programme 19
The line format with book data
 Book_code_title_year_author_numberOfPages where:
 "Book" is a prefix that indicates the line type.
 code is a string that represents the code of the book.
 title is a string that represents the title of the book.
 year is an integer that represents the year the book was
published.
 author is a string that represents the author of the book.
 numberOfPages is an integer that represents the number
of pages in the book.
 The fields are delimited by an underscore ( _ ). The fields
themselves will not contain any underscores.

Object-Oriented Programme 20
The lines format with recording data
 Recording_code_title_year_performer_format where:
 "Recording" is a prefix that indicates the line type.
 code is a string that represents the code of the recording.
 title is a string that represents the title of the recording.
 year is an integer that represents the year of the
recording.
 performer is a string that represents the performer of the
recording.
 format is a string that represents the format of the
recording.
 The fields are delimited by an underscore ( _ ). The fields
themselves will not contain any underscores.

Object-Oriented Programme 21
class diagram
 the elements used to implement this version of the
library system:

Object-Oriented Programme 22
Interface LibraryCatalogLoader
 The interface LibraryCatalogLoader declares a
method that loads a library catalog from a file.
 Method:
Catalog loadCatalog(String filename) throws
FileNotFoundException, IOException,
DataFormatException
 Loads the information in the specified file into the
library catalog.
 Sample code (LibraryCatalogLoader.java )

Object-Oriented Programme 23
Class FileLibraryCatalogLoader
 Sample code(FileLibraryCatalogLoader.java )
 The class FileLibraryCatalogLoader implements
interface LibraryCatalogLoader.
 It is used to load a library catalog from a file.

Object-Oriented Programme 24
Methods study
 publicCatalog loadCatalog(String fileName)
throws FileNotFoundException, IOException,
DataFormatException
 Loads the information in the specified file into a library catalog.
 This method begins by opening the file for reading. It then proceeds
to read each line in the file.
 If the line contains book data, it calls the method readBook to extract
the book information and create a Book object;
 if the line contains recording data, it calls readRecording.
 Finally, loadCatalog adds the book (or recording) to the library
catalog.
 This method can throw the following exceptions:
 FileNotFoundException. If the specified file does not exist.
 IOException. If there is an error reading the information in the specified
file.
 DataFormatException. If a line in the file has errors (the exception
should contain the line of malformed data).
Object-Oriented Programme 25
Methods study
• private Book readBook (String line) throws
DataFormatException
• This method uses the class StringTokenizer to
extract the book data in the specified line.
• If the line is error free, this method returns a
Book object that encapsulates the book data.
• If the line has errors, that is, if it does not have
the expected number of tokens or the tokens that
should contain an integer do not;
• this method throws a Exception that contains the
line of malformed data.
• DataFormatException

Object-Oriented Programme 26
Methods study
 private Recording readRecording(String line)
 This method uses the class StringTokenizer to
extract the recording data in the specified line.
 If the line is error-free, this method returns a
Recording object that encapsulates the recording
data.
 If the line has errors, that is, if it does not have
the expected number of tokens or the token that
should contain an integer does not;
 this method throws a Exception that contains the
line of malformed data.
DataFormatException

Object-Oriented Programme 27
Class DataFormatException
 This exception is thrown when a line in a file being
parsed has errors:
 The line does not have the expected number of
tokens.
 The tokens that should contain numbers do not.
 Sample code(DataFormatException.java)

Object-Oriented Programme 28
Writing Data to a File
 we present a version that saves the borrower
database to a file in those three formats:
 plain text
 HTML
 XML
 Sample code (LibrarySystem.java)

Object-Oriented Programme 29
Note of The method writeFile()
t line 256, receives a file name and a formatted
string containing borrower data.
 In lines 259 and 260, the method creates a new file
(which has the specified name), and then,
 in line 262, the method writes the formatted string
to the new file.
 Note that the formatted string will contain end-of-
line characters ( \n ) because each of the formats
uses end-of-line characters.

Object-Oriented Programme 30
Complete Library System
 The following files implement the other classes in this
version of the library system:
 Book.java
 Recording.java
 CatalogItem.java
 Catalog.java
 Borrower.java
 BorrowedItems.java
 BorrowerDatabase.java
 BorrowersFormatter.java
 PlainTextBorrowersFormatter.java
 HTMLBorrowersFormatter.java
 XMLBorrowersFormatter.java

Object-Oriented Programme 31