Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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

2 1May 2004NH-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.

3 2May 2004NH-Chapter 16 Java Streams Input StreamsOutput Streams ñTwo kinds of data streams: ñByte streams ñCharacter streams ñExamples:  Output stream : System.out (a java.io.PrintStream) ñInput stream : nhUtilities.basicIO.BasicFileReader.

4 3May 2004NH-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.

5 4May 2004NH-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.

6 5May 2004NH-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

7 6May 2004NH-Chapter 16 Byte Input Stream: Standard input stream ñCan read a byte from standard input by writing int b = System.in.read();

8 7May 2004NH-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.

9 8May 2004NH-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, SecurityException public FileInputStream (File file) throws FileNotFoundException, SecurityException public FileInputStream (FileDescriptor fd) throws FileNotFoundException, SecurityException

10 9May 2004NH-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(); }

11 10May 2004NH-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.

12 11May 2004NH-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

13 12May 2004NH-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;

14 13May 2004NH-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.

15 14May 2004NH-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));

16 15May 2004NH-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

17 16May 2004NH-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.

18 17May 2004NH-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; }

19 18May 2004NH-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; }

20 19May 2004NH-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.

21 20May 2004NH-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)

22 21May 2004NH-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

23 22May 2004NH-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

24 23May 2004NH-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

25 24May 2004NH-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.

26 25May 2004NH-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.

27 26May 2004NH-Chapter 16 Implementing readInt  Class 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; }

28 27May 2004NH-Chapter 16 Implementing readInt  readInt ñ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 lastInt. ñmust do a one character “look ahead”.

29 28May 2004NH-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.

30 29May 2004NH-Chapter 16 BasicFileReader constructor implementation private 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); } … }

31 30May 2004NH-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()); } }

32 31May 2004NH-Chapter 16 Output byte streams Abstract 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.

33 32May 2004NH-Chapter 16 FileOutputStream constructors public 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

34 33May 2004NH-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;

35 34May 2004NH-Chapter 16 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.

36 35May 2004NH-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.

37 36May 2004NH-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.

38 37May 2004NH-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

39 38May 2004NH-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.

40 39May 2004NH-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

41 40May 2004NH-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.

42 41May 2004NH-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.

43 42May 2004NH-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.

44 43May 2004NH-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.

45 44May 2004NH-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.


Download ppt "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."

Similar presentations


Ads by Google