8/30/2018 CPRG 215 Introduction to Object-Oriented Programming with Java Module 5- The java.io Package Topic 5.1 Input and Output Streams, Readers and Writers Produced by Harvey Peters, 2008 Copyright SAIT
Please read the following sections in your textbook Core Java, Volume II–Advanced Features, Eighth Edition By Cay S. Horstmann & Gary Cornell Chapter 1 - Streams and Files Streams CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT
java.io Designed for maximum flexibility Numerous classes for specific types of data Handles 8-bit and 16-bit formats to accommodate binary, ASCII and Unicode data Can connect to Keyboard/console Standard Input (STDIN) Standard Output (STDOUT) Standard Error (STDERR) Files Processes Network sockets CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.1
java.io Based on the metaphor of streams of data flowing in and out of a program InputStream and OutputStream are basic classes Build advanced handling by joining objects together CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.1
Input Calling System.in returns an InputStream that is connected to the keyboard This InputStream can be used as a constructor argument to create other streams Each stream has read methods Read at whatever point is needed CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.2
Output Don’t forget to flush the buffer! Output can go to various destinations For files, attach a FileOutputStream to a file To improve efficiency of writing attach a buffer Write to the buffer, data flows through the other objects to the file Don’t forget to flush the buffer! CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.3
Input Stream Methods The three basic read() methods The other methods int read() int read(byte[]) int read(byte[], int, int) The other methods void close() int available() skip(long) boolean markSupported() void mark(int) void reset(int) CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.4
Output Stream Methods The three basic write() methods void write(int) void write(byte[]) void write(byte[], int, int) The other methods void close() void flush() CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.5
Readers and Writers Java is based on Unicode characters - 16 bits Most hardware is 8-bit InputStreams & OutputStreams are 8-bit Read and write bytes Readers & Writers provided to handle 16-bit data Read and Write chars Files can connect to streams or readers & writers Automatic conversion between 16 and 8 bit CPRG 215 Module 5.1- Input and Output Streams, Readers and Writers Copyright SAIT Topic 5.1.6