An Introduction to Programming and Object Oriented Design
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
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 nh. Utilities. basic. IO. Basic. File. Reader ñ 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. May 2004 NH-Chapter 16 1
Java Streams Input Streams Output Streams ñTwo kinds of data streams: ñ Byte streams ñ Character streams ñExamples: ñOutput stream : System. out (a java. io. Print. Stream) ñInput stream : nh. Utilities. basic. IO. Basic. File. Reader. May 2004 NH-Chapter 16 2
Java I/O library structure ñ Four class hierarchies, each topped with an abstract class, supporting reading and writing data streams ñ Input. Stream classes, for reading byte streams. ñ Output. Stream classes, for writing byte streams. ñ Reader classes, for reading character streams. ñ Writer classes, for writing character streams. May 2004 NH-Chapter 16 3
Byte Input Streams: Abstract class Input. Stream ñ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 ñ Client method invoking read/close must either catch Close theor input streamaand releaseclause associated IOexception include throws in itsresources. header. May 2004 NH-Chapter 16 4
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 May 2004 static final Input. Stream in; // standard input NH-Chapter 16 5
Byte Input Stream: Standard input stream ñ Can read a byte from standard input by writing int b = System. in. read(); standard input: bytes from keyboard Application May 2004 NH-Chapter 16 6
Byte Input Stream: File. Input. Stream ñ Subclass of Input. Stream. ñ Specifies a file as the stream source. ñ File is specified in the File. Input. Stream constructor, by either ñ a String file name, ñ a File object, ñ or a system-specific file descriptor ñ File is opened when File. Input. Stream is created. May 2004 NH-Chapter 16 7
Byte Input Stream: File. Input. Stream constructors public File. Input. Stream (String name) throws File. Not. Found public File. Input. Stream (File file) throws File. Not. Found. Exc public File. Input. Stream (File. Descriptor fd) throws File. Not ñ String name is a system-dependent file name. ñ File is an abstract, system-independent representation of a pathname. ñ File. Descriptor is a handle to the underlying machine-specific structure representing an open file or other byte source. May 2004 NH-Chapter 16 8
Reading bytes from a file public void process. File (String file. Name) throws IOExc File. Input. Stream in = new File. Input. Stream(file. Nam int b; while ((b = in. read()) != -1) { process b } in. close(); } May 2004 NH-Chapter 16 9
Byte Input Stream: Buffered. Input. Stream ñ Uses buffer to store input from the stream. ñ A subclasses of Input. Stream and Filter. Input. Stream, and wraps an Input. Stream provided as a constructor argument: public Buffered. Input. Stream (Input. Stream in) Create a Buffered. Input. Stream that buffers input from the given Input. Stream in a buffer with the default size of 2048 bytes. May 2004 NH-Chapter 16 10
Input character streams: Abstract class Reader ñ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 ñ Method returns a value of type int, not of type char. ñ Postcondition ensures that int can be safely cast to a char. May 2004 NH-Chapter 16 11
Input character streams: Buffered. Reader ñ Class Buffered. Reader ñ Buffered. Reader buffers character stream input in much the same way that Buffered. Input. Stream is used to buffer byte stream input. ñ Provides a method to read a line of characters: public String read. Line() throws IOException; May 2004 NH-Chapter 16 12
Input character streams: Input. Stream. Reader ñ Wraps an Input. Stream and provides Reader functionality. ñ Converts each Input. Stream byte to Unicode character using default or specified encoding scheme. May 2004 NH-Chapter 16 13
Input. Stream. Reader constructors public Input. Stream. Reader (Input. Stream in) Translates bytes to characters using system default encoding. public Input. Stream. Reader (Input. Stream in, String enc) throws Unsupported. Encoding. Exception Translates bytes to characters using specified encoding. ñ For efficiency, an Input. Stream. Reader is often wrapped in a Buffered. Reader: Buffered. Reader in = new Buffered. Reader( new input. Stream. Reader(System. in)); May 2004 NH-Chapter 16 14
Input character streams: File. Reader ñ File. Reader extends Input. Stream. Reader. ñ File. Reader is an Input. Stream. Reader using system default encoding and wrapped around a File. Input. Stream. ñ constructors : public File. Reader (String name) throws File. Not. Found. Exception, Security. Exception public File. Reader (File file) throws File. Not. Found. Exception, Security. Exception public File. Reader (File. Descriptor fd) throws File. Not. Found. Exception, Security. Exception May 2004 NH-Chapter 16 15
Example ñRead a binary file and writes out the bytes, as two hexadecimal digits. public void display. Binary. File (String file. Name) throws IOException { Buffered. Input. Stream in = new Buffered. Input. Stream( new File. Input. Stream(file. Name)); int b; while ((b = in. read()) != -1) { String hex = Integer. to. String(b, 16); if (hex. length() == 1) hex = '0' + hex; System. out. println(hex); } in. close(); } May 2004 NH-Chapter 16 16
Example ñ Read a text file, and counts number of occurrences of a given character in file. public int char. Count (char c, String file. Name) throws IOException { File. Reader in = new File. Reader(file. Name); int count = 0; int char. Read; while ((char. Read = in. read()) != -1) if ((char)char. Read == c) count = count + 1; in. close(); return count; } May 2004 NH-Chapter 16 17
Example ñ Count number of lines in input file that begin with a specified character. ñ We wrap File. Reader with a Buffered. Reader to use Buffered. Reader’s read. Line method. public int char. Count (char c, String file. Name) throws IOException { Buffered. Reader in = new Buffered. Reader( new File. Reader(file. Name)); int count = 0; String line; while ((line = in. read. Line()) != null) if (line. char. At(0) == c) count = count + 1; in. close(); return count; } May 2004 NH-Chapter 16 18
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 nh. Utilities. basic. IO. Basic. File. Reader 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. May 2004 NH-Chapter 16 19
Class Simple. Input 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 Simple. Input public static int read. Int (String message) public static double read. Double (String message) public static char read. Char (String message) public static String read. String (String message) May 2004 NH-Chapter 16 20
Example of use of Simple. Input ñ A client will invoke a method something like this: int age = Simple. Input. read. Int("Enter your age: "); ñ The user will see prompt, and key in an integer, Enter your age: 32 User’s input prompt May 2004 NH-Chapter 16 21
Simple. Input class implementation public class Simple. Input { private static Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(System. in)); public static int read. Int (String message) throws IOException, Number. Format. Exception { prompt(message); return Integer. parse. Int(in. read. Line()); } public static double read. Double (String message) throws IOException, Number. Format. Exception { prompt(message); return Double. parse. Double(in. read. Line()); } May 2004 NH-Chapter 16 22
Simple. Input class implementation public static char read. Char (String message) throws IOException { prompt(message); return in. read. Line(). char. At(0); } public static String read. String (String message) throws IOException { prompt(message); return in. read. Line(); } private static void prompt (String message) { System. out. print(message); System. out. flush(); } }//end Simple. Input May 2004 NH-Chapter 16 23
Simple. Input 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. May 2004 NH-Chapter 16 24
nh. Utilities. basic. IO. Basic. File. Reader ñClass has two constructors: public Basic. File. Reader () Create a Basic. File. Reader attached to standard input. public Basic. File. Reader (String file. Name) Create a Basic. File. Reader attached to the named file. ñ Methods are proper queries or proper commands. ñ Commands skips white space, read optional sign. ñ It defines its own Runtime. Exceptions exceptions: nh. Utilities. basic. IOException, nh. Utilites. basic. IO. EOFException, nh. Utilities. basic. IO. Data. Exception May 2004 NH-Chapter 16 25
Implementing read. Int ñClass has instance variable last. Int containing value of most recently read integer: private int last. Int; ñMethod last. Int returns value of instance variable: public int last. Int () { return this. last. Int; } May 2004 NH-Chapter 16 26
Implementing read. Int ñMust skip any leading white space in the input stream; ñMust check for a sign; ñMust read the digits and store the value denoted in last. Int. ñmust do a one character “look ahead”. May 2004 NH-Chapter 16 27
Implementing read. Int: Pushback. Reader ñ To detect end of digit stream, must read character after digit string. ñ Need to “put back in stream” a character after read. ñ Use class Pushback. Reader public Pushback. Reader (Reader in) ñTo push back character use unread: public void unread (int c) throws IOException Pushes back a single character into stream. May 2004 NH-Chapter 16 28
Basic. File. Reader constructor implementation private Pushback. Reader in; public Basic. File. Reader () { in = new Pushback. Reader(new Buffered. Reader( new Input. Stream. Reader(System. in))); … } public Basic. File. Reader (String file. Name) { try { in = new Pushback. Reader(new Buffered. Reader( new File. Reader(file. Name))); } catch (java. io. File. Not. Found. Exception e) { throw new IOException("File not found: " + file. Name); } … } May 2004 NH-Chapter 16 29
public void read. Int () { try { int sign = 1; int inchar = skip. Space(); 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. is. Digit((char)inchar)) { in. unread(inchar); throw new Data. Exception( "Encountered " + inchar + "; expected digit"); } last. Int = 0; while (Character. is. Digit((char)inchar)) { last. Int = 10*last. Int + Character. digit((char)inchar, 10); inchar = in. read(); } last. Int = last. Int*sign; if (inchar != -1) in. unread(inchar); } }catch (java. io. IOException e) { throw new IOException(e. get. Message()); } May 2004 NH-Chapter 16 30
Output byte streams Abstract class Output. Stream ñ 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. May 2004 NH-Chapter 16 31
File. Output. Stream constructors public File. Output. Stream (String name) throws File. Not. Found. Exception, Security. Exception public File. Output. Stream (String name, boolean append) throws File. Not. Found. Exception, Security. Exception public File. Output. Stream (File file, boolean append) throws File. Not. Found. Exception, Security. Exception public File. Output. Stream (File. Descriptor fd) throws File. Not. Found. Exception, Security. Exception May 2004 NH-Chapter 16 32
Print. Stream ñ Adds ability to print representations of various data values conveniently. ñ Unlike other output streams, a Print. Stream never throws an IOException. ñ Commonly used Print. Streams: standard output and standard error. ñ Standard output and standard error are constants defined in the class java. lang. System: public static final Print. Stream out; public static final Print. Stream err; May 2004 NH-Chapter 16 33
Output character streams Abstract 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. May 2004 NH-Chapter 16 34
Buffered. Reader, Output. Stream. Writer, File. Writer ñ Buffered. Writer extends Writer, and is symmetric to Buffered. Reader. ñ Output. Stream. Writer adapts an Output. Stream to a Writer, and is symmetric to Input. Stream. Reader. ñ File. Writer extends Output. Stream. Writer similarly to File. Reader’s extension of Input. Stream. Reader. May 2004 NH-Chapter 16 35
Print. Writer ñ Extends and wraps a Writer, provides functionality for writing string representations of primitive values and objects. public Print. Writer (Output. Stream out) Create a Print. Writer that sends output to specified Output. Stream. An Output. Stream. Writer that converts characters to bytes using system default encoding is constructed. public Print. Writer (Output. Stream out, boolean auto. Flush) As above and if auto. Flush is true, calls its flush method after every invocation of println. public Print. Writer (Writer out) Create a Print. Writer that sends output to the specified Writer. public Print. Writer (Writer out, boolean auto. Flush) Creates Print. Writer that outputs to specified Writer. Same as above for auto. Flush. May 2004 NH-Chapter 16 36
Print. Writer 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 to. String method May 2004 NH-Chapter 16 37
Summary ñ Review basic classes in the java. io stream library. ñ There are four root classes, one for each category of stream: ñ Input. Stream models input byte streams, ñ Reader models input character streams, ñ Output. Stream 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. May 2004 NH-Chapter 16 38
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 May 2004 NH-Chapter 16 39
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. May 2004 NH-Chapter 16 40
Summary ñ Classes Input. Stream. Reader and Output. Stream. Writer are Reader and Writer subclasses that wrap an Input. Stream and Output. Stream respectively. ñ An Input. Stream. Reader converts each byte of input to a 16 -bit character using a system default or specified encoding. ñ Output. Stream. Writer converts each 16 -bit character to a byte, again using a system default or specified encoding. May 2004 NH-Chapter 16 41
Summary ñ File. Input. Stream, File. Output. Stream, File. Reader, and File. Writer 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. May 2004 NH-Chapter 16 42
Summary ñ There are three standard predefined streams available to every application: ñ System. in, an Input. Stream. ñ System. out, a Print. Stream. ñ System. err, a Print. Stream. ñ Print. Stream is a Filter. Output. Stream with a number of useful methods for writing out character representations of values. May 2004 NH-Chapter 16 43
Summary ñ A particularly useful output class is Print. Writer. ñ A Print. Writer is a Writer with methods similar to Print. Stream’s for converting values to character strings. ñ The characters are converted to bytes using a system default encoding before being written to an Output. Stream. May 2004 NH-Chapter 16 44
- Slides: 45