240 likes | 245 Views
www.espirity.com. Streams. Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com). Additional Contributors. None as of September, 2004. Module Overview. Streams. Module Road Map. Streams What are streams? Stream types Character streams Byte streams Filter streams
E N D
www.espirity.com Streams Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)
Additional Contributors • None as of September, 2004
Module Overview Streams
Module Road Map • Streams • What are streams? • Stream types • Character streams • Byte streams • Filter streams • Object Serialization
What is a Stream? • From an abstract point of view a stream is simply a sequence • From an implementation point of view you can think of a stream as a list • A stream has a start, and end, and a position • Streams can let us model systems that have state without ever using assignment or mutable data
Stream Concept • To read data serially, a Java program: • Opens a stream to a data source • file • remote socket • Reads the information serially • To write data serially, a Java program: • Opens a stream to a data source • Writes the information serially • Data source type doesn’t matter, concepts of reading and writing are the same • Once you understand the top level classes (java.io.Reader, java.io.Writer), the remaining classes are much of the same
Stream Types • Two different types of streams: • Character streams • Support reading and writing of characters, text • Contain 16-bit Unicode characters • Supported through Reader and Writer classes • Byte streams • Support reading and writing of any bytes • Contain 8-but bytes • Supported through InputStream and OutputStream classes • It is possible to do conversion between character streams and byte stream • InputStreamReader and OutputStreamWriter classes can be used
Character Streams vs. Byte Streams • Character streams (reader and writer) should be used because: • They can handle any character in the Unicode character set (while the byte streams are limited to ISO-Latin-1 8-bit bytes) • They are easier to internationalize because they are not dependent upon a specific character encoding • They use buffering techniques internally and are therefore potentially much more efficient than byte streams • Byte streams should be used for handling binary data, such as image and sound files • All stream classes are in the java.io package
Character Streams Hierarchy Object InputStream Reader OutputStream Writer <<abstract>> Reader <<abstract>> Writer FileReader BufferedReader FileWriter BufferedWriter
Reader and Writer classes • Parent classes for character-stream based classes • Used to read and write 16-bit character streams • Important methods for reading and writing to streams found in these and their descendent classes include the following: int read() int read(char buffer[]) int read(char buffer[], int offset, int length) int write(int aCharacter) int write(char buffer[]) int write(char buffer[], int offset, int length)
FileReader and FileWriter classes • FileReader is used for reading streams of characters from a file • FileWriter is used for writing streams of characters to a file File inputFile = new File("source.txt"); File outputFile = new File("final.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int aCharacter; while ((aCharacter = in.read()) != 1) out.write(aCharacter); in.close(); out.close(); It’s important to close the stream
Writing and Reading Example • Create a file • Read the file FileWriter writefile = new FileWriter("source.txt"); writefile.write('A'); writefile.write("bcdefghi"); writefile.close(); myString Abcdefghi FileReader inFile = new FileReader("source.txt"); inFile.skip(3); // skips next 3 chars ('A' 'b' 'c' ) char[] characterArray = new char[10]; inFile.read(characterArray ); // ['d' 'e' 'f' 'g' 'h' 'i'] String myString = new inFile.read(characterArray).trim(); inFile.close();
BufferedReader and BufferedWriter classes • Used for buffering characters as being read or written • Buffer is used for storing data without conversion • Buffer size can be set • Should wrap any reader/writer whose read/write operations may be inefficient BufferedReader reader = new BufferedReader(new DataInputStream(System.in)); String input; while ((input = reader.readLine()) != null) { ... //do something interesting here }
Byte Streams Hierarchy InputStream FileInputStream FilterInputStream ObjectInputStream DataInputStream BufferdInputStream Filter streams Filter streams Object streams OuputStream FileOutputStream FilterOutputStream ObjectOutputStream DataOutputStream BufferdOutputStream PrintStream
Specialized Byte Streams • File streams • Used for writing data to files and reading data from files • Object streams • Used for reading and writing objects • Also called object serialization • Filter streams • Used for filtering data as it’s being read from streams, or written to the streams • They work with primitive data types (int, double, boolean) • They implement DataInput and DataOutput interfaces
Filter Streams • Filter data as it's being read from or written to a stream • Subclasses of the FilterInputStream a and FilterOutputStream • Constructed on another stream (the underlying stream) • Read method reads input from the underlying stream, filters it, and passes on the filtered data to the caller • Write method writes data to the underlying stream • Filtering done by the streams depends on the stream • Some streams buffer the data, some count data as it goes by, and others convert data to another form
Using Filter Streams… • For reading primitive data types • DataInputStream class can be used FileInputStream inputFile = new FileInputStream("price.cat"); DataInputStream inputStream = new DataInputStream(inputFile); double price= inputStream.readDouble(); inputStream.close(); It’s important to know what’s in the stream
…Using Filter Streams • For writing primitive data types • A DataOutputStream can be used FileOutputStream outputFile = new FileInputStream("price.cat"); DataOutputStream outputStream = new DataInputStream(outputFile ); outputStream.writeDouble(234.56); outputStream.flush(); outputStream.close(); Forces data to be written
Streams in System Class • System.in - standard input • An instance of BufferedInputStream class • Used to read lines of text that user enters • System.out - standard output • Instance of PrintStream class • Used to send text to the Console • System.err - error output • Instance of PrintStream class • Used to send error text to the error file BufferedReader reader = new BufferedReader(new DataInputStream(System.in)); String input; while ((input = reader.readLine()) != null){ System.out.println(input);}
Object Serialization • Supported with ObjectOutputStream class • Serialized object class must implement the Serializable interface GregorianCalendar calendar = new GregorianCalendar(); ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("calendar.dat")); out.writeObject(calendar); out.close(); publicclass java.util.GregorianCalendar extents java.util.Calendar{… publicclass java.util. GregorianCalendar extents java.lang.Object implements java.lang.Cloneable, java.io.Serializable{…
Serialization Protocol • Classes that perform serialization and deserialization must implement special methods: • Object state is saved by writing the individual fields to the ObjectOutputStream • Object state is retrieved by reading the individual fields back from the ObjectInputStream privatevoid writeObject(java.io.ObjectOutputStream out) throws IOException privatevoid readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
Object Deserialization • Supported with ObjectInputStream class • You must know the order in which things were written in order to cast to the correct type ObjectInputStream in = new ObjectInputStream (new FileInputStream("calendar.dat")); GregorianCalendar calendar = (GregorianCalendar)in.readObject(); in.close(); It’s important to know what’s in the stream for casting
Module Summary • In this module you have learned: • What streams are • What are different types of streams in Java • Differences between character streams and byte streams • What filter streams are • Streams used in the System class • How to serialize objects
Labs Slide! Lab: Steams