an introduction to programming and object oriented design using java 2 nd edition. may 2004 jaime...

45
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

Upload: araceli-garden

Post on 02-Apr-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

An Introduction to Programming and Object

Oriented Design using Java2nd Edition. May 2004

Jaime NiñoFrederick Hosch

Chapter 16: Stream I/O

Page 2: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

2May 2004 NH-Chapter 16

Objectives

After studying this chapter you should understand the following: byte streams and character streams, and the class structure

of the standard libraries for manipulating these streams

how to use the standard libraries to construct a utility class such as nhUtilities.basicIO.BasicFileReader

Also, you should be able to: use standard Java stream classes to read and write bytes

and characters;

define input classes designed for specific purposes.

Page 3: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

3May 2004 NH-Chapter 16

Java Streams

Application… b b b b b b b b b …

… b b b b b b b b b …

… b b b b b b b b b …

… b b b b b b b b b …

Input Streams Output Streams

Two kinds of data streams: Byte streams Character streams

Examples: Output stream : System.out (a java.io.PrintStream)Input stream : nhUtilities.basicIO.BasicFileReader.

Page 4: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

4May 2004 NH-Chapter 16

Java I/O library structure

Four class hierarchies, each topped with an abstract class, supporting reading and writing data streams InputStream classes, for reading byte streams.

OutputStream classes, for writing byte streams.

Reader classes, for reading character streams.

Writer classes, for writing character streams.

Page 5: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

5May 2004 NH-Chapter 16

Byte Input Streams:Abstract class InputStream

Client method invoking read/close must either catch IOexception or include a throws clause in its header.

Methods for reading a byte stream includes:public abstract int read () throws IOException

Read and return the next byte of data from the input stream. Return -1 if the end of the stream is encountered.

ensure: (0 <= this.read() && this.read() <=

255) ||this.read() == -1

public void close () throws IOException

Close the input stream and release associated resources.

Page 6: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

6May 2004 NH-Chapter 16

Byte Input Stream:Standard input stream

Input byte stream generally available in every program. Default source of bytes is keyboard. Can be accessed by constant in from class java.lang.System:

public static final InputStream in;// standard input

Page 7: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

7May 2004 NH-Chapter 16

Byte Input Stream:Standard input stream

Can read a byte from standard input by writingint b = System.in.read();

standard input:

Application

bytes from keyboard

Page 8: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

8May 2004 NH-Chapter 16

Byte Input Stream:FileInputStream

Subclass of InputStream.

Specifies a file as the stream source.

File is specified in the FileInputStream constructor, by either a String file name, a File object, or a system-specific file descriptor

File is opened when FileInputStream is created.

Page 9: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

9May 2004 NH-Chapter 16

Byte Input Stream:FileInputStream constructors

String name is a system-dependent file name. File is an abstract, system-independent representation of a

pathname. FileDescriptor is a handle to the underlying machine-specific

structure representing an open file or other byte source.

public FileInputStream (String name) throws FileNotFoundException, SecurityExceptionpublic FileInputStream (File file) throws FileNotFoundException, SecurityExceptionpublic FileInputStream (FileDescriptor fd) throws FileNotFoundException, SecurityException

Page 10: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

10May 2004 NH-Chapter 16

Reading bytes from a file

public void processFile (String fileName) throws IOException {FileInputStream in = new FileInputStream(fileName);int b;while ((b = in.read()) != -1) {

process b}in.close();

}

Page 11: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

11May 2004 NH-Chapter 16

Byte Input Stream:BufferedInputStream

Uses buffer to store input from the stream. A subclasses of InputStream and FilterInputStream,

and wraps an InputStream provided as a constructor argument:

public BufferedInputStream (InputStream in)Create a BufferedInputStream that buffers input from the given InputStream in a buffer with the default size of 2048 bytes.

Page 12: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

12May 2004 NH-Chapter 16

Input character streams:Abstract class Reader

Method returns a value of type int, not of type char. Postcondition ensures that int can be safely cast to

a char.

Reader reads stream of Unicode characters rather than bytes.

public int read () throws IOException

Read and return next data character from the input stream. Character is returned as integer in range 0 to 65535. Return -1 if end of stream.

ensure: (0 <= this.read() && this.read() <=

65535) ||this.read() == -1

Page 13: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

13May 2004 NH-Chapter 16

Input character streams: BufferedReader

Class BufferedReader

BufferedReader buffers character stream input in much the same way that BufferedInputStream is used to buffer byte stream input.

Provides a method to read a line of characters:public String readLine() throws IOException;

BufferedReader

Reader

wraps

Page 14: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

14May 2004 NH-Chapter 16

Input character streams: InputStreamReader

Wraps an InputStream and provides Reader functionality.

Converts each InputStream byte to Unicode character using default or specified encoding scheme.

InputStreamReader

Reader

wrapsInputStream

Page 15: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

15May 2004 NH-Chapter 16

InputStreamReader constructors

For efficiency, an InputStreamReader is often wrapped in a BufferedReader:

public InputStreamReader (InputStream in)

Translates bytes to characters using system default encoding.

public InputStreamReader (InputStream in, String enc)throws UnsupportedEncodingException

Translates bytes to characters using specified encoding.

BufferedReader in = new BufferedReader(new inputStreamReader(System.in));

Page 16: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

16May 2004 NH-Chapter 16

Input character streams: FileReader

FileReader extends InputStreamReader. FileReader is an InputStreamReader using system default

encoding and wrapped around a FileInputStream. constructors :

public FileReader (String name)throws FileNotFoundException, SecurityException

public FileReader (File file)throws FileNotFoundException, SecurityException

public FileReader (FileDescriptor fd)throws FileNotFoundException, SecurityException

Page 17: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

17May 2004 NH-Chapter 16

Example

public void displayBinaryFile (String fileName) throws IOException {

BufferedInputStream in =new BufferedInputStream(

new FileInputStream(fileName));int b;while ((b = in.read()) != -1) {

String hex = Integer.toString(b,16);if (hex.length() == 1)

hex = '0' + hex;System.out.println(hex);

}in.close();

}

Read a binary file and writes out the bytes, as two hexadecimal digits.

Page 18: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

18May 2004 NH-Chapter 16

Example

Read a text file, and counts number of occurrences of a given character in file.

public int charCount (char c, String fileName) throws IOException {

FileReader in = new FileReader(fileName);int count = 0;int charRead;while ((charRead = in.read()) != -1)

if ((char)charRead == c)count = count + 1;

in.close();return count;

}

Page 19: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

19May 2004 NH-Chapter 16

Example Count number of lines in input file that begin with a

specified character. We wrap FileReader with a BufferedReader to use

BufferedReader’s readLine method.public int charCount (char c, String fileName)

throws IOException {BufferedReader in = new BufferedReader(

new FileReader(fileName));int count = 0;String line;while ((line = in.readLine()) != null)

if (line.charAt(0) == c)count = count + 1;

in.close();return count;

}

Page 20: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

20May 2004 NH-Chapter 16

Reading String representations of primitive values

Input classes in java.io do not include facilities for easily parsing character sequences that represent primitive values such as numbers.

We built nhUtilities.basicIO.BasicFileReader to include in our libraries to fill this need.

Construct a set of methods that allow us to read representations of integers and doubles from standard input.

Page 21: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

21May 2004 NH-Chapter 16

Class SimpleInput specifications Each method writes prompt message to standard output, and

return user’s response from standard input.

User’s input must have format specified by name of method.

public class SimpleInput

public static int readInt (String message)

public static double readDouble (String message)

public static char readChar (String message)

public static String readString (String message)

Page 22: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

22May 2004 NH-Chapter 16

Example of use of SimpleInput

A client will invoke a method something like this:

int age = SimpleInput.readInt("Enter your age: ");

The user will see prompt, and key in an integer,

User’s input

prompt

Enter your age: 32

Page 23: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

23May 2004 NH-Chapter 16

public class SimpleInput {

private static BufferedReader in =new BufferedReader(new InputStreamReader(System.in));

public static int readInt (String message)throws IOException, NumberFormatException {prompt(message);return Integer.parseInt(in.readLine());

}

public static double readDouble (String message)throws IOException, NumberFormatException {prompt(message);return Double.parseDouble(in.readLine());

}

SimpleInput class implementation

Page 24: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

24May 2004 NH-Chapter 16

public static char readChar (String message)throws IOException {prompt(message);return in.readLine().charAt(0);

}

public static String readString (String message)throws IOException {prompt(message);return in.readLine();

}

private static void prompt (String message) {System.out.print(message);System.out.flush();

}

}//end SimpleInput

SimpleInput class implementation

Page 25: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

25May 2004 NH-Chapter 16

SimpleInput class deficiencies

Input can be read only from standard input.

Only one value per line can be read.

Doubles can begin with ‘+’ or ‘-’ and be preceded and followed by blanks; integer cannot be preceded by ‘+’ and cannot be preceded or followed by blanks.

Methods are neither proper queries not proper commands. They change state of input stream like commands, but return values like queries.

Page 26: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

26May 2004 NH-Chapter 16

nhUtilities.basicIO.BasicFileReader

Methods are proper queries or proper commands. Commands skips white space, read optional sign. It defines its own RuntimeExceptions exceptions:

nhUtilities.basicIO.IOException, nhUtilites.basicIO.EOFException,

nhUtilities.basicIO.DataException

Class has two constructors:

public BasicFileReader ()Create a BasicFileReader attached to standard input.

public BasicFileReader (String fileName)Create a BasicFileReader attached to the named file.

Page 27: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

27May 2004 NH-Chapter 16

Implementing readIntClass has instance variable lastInt containing value of most recently read integer:

private int

lastInt;Method lastInt returns value of instance variable:

public int lastInt () { return this.lastInt; }

Page 28: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

28May 2004 NH-Chapter 16

Implementing readInt

readIntMust skip any leading white space in the input stream;

Must check for a sign;

Must read the digits and store the value denoted in lastInt.

must do a one character “look ahead”.

Page 29: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

29May 2004 NH-Chapter 16

Implementing readInt: PushbackReader

To detect end of digit stream, must read character after digit string.

Need to “put back in stream” a character after read.

Use class PushbackReader

To push back character use unread:

public PushbackReader (Reader in)

public void unread (int c) throws IOException

Pushes back a single character into stream.

Page 30: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

30May 2004 NH-Chapter 16

BasicFileReader constructor implementationprivate PushbackReader in;

public BasicFileReader () {in = new PushbackReader(new BufferedReader(

new InputStreamReader(System.in)));…

}

public BasicFileReader (String fileName) {try {

in = new PushbackReader(new BufferedReader(new FileReader(fileName)));

} catch (java.io.FileNotFoundException e) {throw new IOException("File not found: " +

fileName); }…

}

Page 31: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

31May 2004 NH-Chapter 16

public void readInt () { try {

int sign = 1;int inchar = skipSpace();

if ((char)inchar == '-') sign = -1;if ((char)inchar == '+' || (char)inchar == '-') inchar = in.read();if (inchar == -1)throw new EOFException(

"Encountered EOF; expected digit"); else if (!Character.isDigit((char)inchar)) {

in.unread(inchar); throw new DataException(

"Encountered " + inchar + "; expected digit"); }lastInt = 0;while (Character.isDigit((char)inchar)) { lastInt = 10*lastInt + Character.digit((char)inchar,10); inchar = in.read();}lastInt = lastInt*sign;if (inchar != -1) in.unread(inchar);

}catch (java.io.IOException e) {throw new IOException(e.getMessage()); }

}

Page 32: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

32May 2004 NH-Chapter 16

Output byte streamsAbstract class OutputStream

Top of the output byte stream hierarchy. Methods include:

public abstract void write (int b) throws IOException

Write byte (low order 8 bits of int provided) to the output stream.

public void close () throws IOException

Close output stream and release any associated resources.

public void flush () throws IOException

Write any buffered bytes to output stream.

Page 33: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

33May 2004 NH-Chapter 16

FileOutputStream constructorspublic FileOutputStream (String name)

throws FileNotFoundException, SecurityException

public FileOutputStream (String name, boolean append)throws FileNotFoundException, SecurityException

public FileOutputStream (File file)throws FileNotFoundException, SecurityException

public FileOutputStream (File file, boolean append)throws FileNotFoundException, SecurityException

public FileOutputStream (FileDescriptor fd)throws FileNotFoundException, SecurityException

Page 34: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

34May 2004 NH-Chapter 16

PrintStream

Adds ability to print representations of various data values conveniently.

Unlike other output streams, a PrintStream never throws an IOException.

Commonly used PrintStreams: standard output and standard error.

Standard output and standard error are constants defined in the class java.lang.System:

public static final PrintStream out;

public static final PrintStream err;

Page 35: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

35May 2004 NH-Chapter 16

Output character streamsAbstract class Writer

Writer: top of output character stream hierarchy.

Its write method writes a Unicode characters.

public abstract void write (int c) throws IOException

Write a character consisting of the low order 16 bits of the int provided to the output stream.

Page 36: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

36May 2004 NH-Chapter 16

BufferedReader, OutputStreamWriter, FileWriter

BufferedWriter extends Writer, and is symmetric to BufferedReader.

OutputStreamWriter adapts an OutputStream to a Writer, and is symmetric to InputStreamReader.

FileWriter extends OutputStreamWriter similarly to FileReader’s extension of InputStreamReader.

Page 37: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

37May 2004 NH-Chapter 16

PrintWriter

Extends and wraps a Writer, provides functionality for writing string representations of primitive values and objects.

public PrintWriter (OutputStream out)Create a PrintWriter that sends output to specified OutputStream. An OutputStreamWriter that converts characters to bytes using system default encoding is constructed.

public PrintWriter (OutputStream out,boolean autoFlush)As above and if autoFlush is true, calls its flush method after every invocation of println.

public PrintWriter (Writer out)Create a PrintWriter that sends output to the specified Writer.

public PrintWriter (Writer out, boolean autoFlush)Creates PrintWriter that outputs to specified Writer. Same as above for autoFlush.

Page 38: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

38May 2004 NH-Chapter 16

PrintWriter methods

Provides overloaded version of print and println methods for each primitive value, as well as objects and strings.

For objects it uses Object’s toString method

Page 39: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

39May 2004 NH-Chapter 16

Summary

Review basic classes in the java.io stream library.

There are four root classes, one for each category of stream: InputStream models input byte streams, Reader models input character streams, OutputStream models output byte stream, and Writer models output character streams.

Character streams in Java represent characters with a 16-bit Unicode encoding. Any other stream is considered a byte stream.

Page 40: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

40May 2004 NH-Chapter 16

Summary

Classes add functionality to the root classes by extension and composition. Each root class has a corresponding Filter class that serves as a basis for extension

Filter

Root

wraps

Page 41: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

41May 2004 NH-Chapter 16

Summary

Filter both extends and wraps root class.

It adds no new functionality, it forwards all requests to the component root class instance.

Functionality is added by extending the Filter.

Since the Filter is a subclass of the root, functionality can be accumulated by having one Filter wrap another.

Page 42: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

42May 2004 NH-Chapter 16

Summary

Classes InputStreamReader and OutputStreamWriter are Reader and Writer subclasses that wrap an InputStream and OutputStream respectively.

An InputStreamReader converts each byte of input to a 16-bit character using a system default or specified encoding.

OutputStreamWriter converts each 16-bit character to a byte, again using a system default or specified encoding.

Page 43: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

43May 2004 NH-Chapter 16

Summary

FileInputStream, FileOutputStream, FileReader, and FileWriter allow a file to be specified as stream source or destination.

The file can be specified by name, with a File object, or with a file descriptor.

Page 44: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

44May 2004 NH-Chapter 16

Summary

There are three standard predefined streams available to every application: System.in, an InputStream. System.out, a PrintStream. System.err, a PrintStream.

PrintStream is a FilterOutputStream with a number of useful methods for writing out character representations of values.

Page 45: An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O

45May 2004 NH-Chapter 16

Summary

A particularly useful output class is PrintWriter.

A PrintWriter is a Writer with methods similar to PrintStream’s for converting values to character strings.

The characters are converted to bytes using a system default encoding before being written to an OutputStream.