Presentation is loading. Please wait.

Presentation is loading. Please wait.

Streams Dwight Deugo ( Nesa Matic ( Portions of the notes for this lecture include excerpts from.

Similar presentations

Presentation on theme: "Streams Dwight Deugo ( Nesa Matic ( Portions of the notes for this lecture include excerpts from."— Presentation transcript:

1 Streams Dwight Deugo (
Nesa Matic Portions of the notes for this lecture include excerpts from the Eclipse 3.0 Help facility. These excerpts are made available under CPL for ease of use by instructors, (c) Copyright (c) 2000, 2004 IBM Corporation and others. For more complete information instructors are encouraged to read the full notes from the Eclipse Help facility.

2 Additional Contributors
None as of September, 2004

3 Module Overview Streams In this section we discuss Streams in Java.

4 Module Road Map Streams What are streams? Stream types
Character streams Byte streams Filter streams Object Serialization The module road map slide gives a view on what sections are in the module and what are the topics covered in the current section.

5 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 It is possible to model bank account using streams and without using assignment operation or mutable data. All bank transactions can be in the stream and account balance could be calculated by moving through the stream of transactions, instead of modeling it as a field in BankAccount class.

6 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: 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 (,, the remaining classes are much of the same

7 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

8 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 package

9 Character Streams Hierarchy
Object InputStream Reader OutputStream Writer <<abstract>> Reader <<abstract>> Writer FileReader BufferedReader FileWriter BufferedWriter

10 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)

11 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 = != 1) out.write(aCharacter); in.close(); out.close(); FileReader class inherits from InputStremaReader class that inherits from Reader class. FileWriter class inherits from OutoutStremaReader class that inherits from Writer class. It’s important to close the stream

12 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]; ); // ['d' 'e' 'f' 'g' 'h' 'i'] String myString = new; inFile.close();

13 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(; String input; while ((input = reader.readLine()) != null) { ... //do something interesting here } Using BufferedReader and BufferedWriter classes may be very efficient in improving overall performance of reading data from streams and writing data to streams. Without them each read or write operation on data results in data being read/written and converted into characters/bytes right away, which may be time consuming. With buffered reader/writer, read and write operations only read/write data without converting them. The conversion is done when streams close, or when buffer is full.

14 Byte Streams Hierarchy
InputStream FileInputStream FilterInputStream ObjectInputStream DataInputStream BufferdInputStream Filter streams Filter streams Object streams OuputStream In the next few slides we will look at the byte streams hierarchy and most commonly used byte stream classes. FileOutputStream FilterOutputStream ObjectOutputStream DataOutputStream BufferdOutputStream PrintStream

15 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

16 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

17 Using Filter Streams… For reading primitive data types
DataInputStream class can be used FileInputStream inputFile = new FileInputStream(""); DataInputStream inputStream = new DataInputStream(inputFile); double price= inputStream.readDouble(); inputStream.close(); It’s important to know what’s in the stream

18 …Using Filter Streams For writing primitive data types
A DataOutputStream can be used FileOutputStream outputFile = new FileInputStream(""); DataOutputStream outputStream = new DataInputStream(outputFile ); outputStream.writeDouble(234.56); outputStream.flush(); outputStream.close(); Forces data to be written flush() method forces data to be written. If not used, data are written either when stream is closed or when buffer is full.

19 Streams in System Class - 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 Used to send error text to the error file BufferedReader reader = new BufferedReader(new DataInputStream(; String input; while ((input = reader.readLine()) != null){ System.out.println(input);}

20 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(); Above example shows GregorianCalendar being serialized into a file. It is possible to serialize an instance of this class as its super class (Calendar) implements Serializable interface. public class java.util.GregorianCalendar extents java.util.Calendar{… public class java.util. GregorianCalendar extents java.lang.Object implements java.lang.Cloneable,{…

21 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 private void writeObject( out) throws IOException private void readObject( in) throws IOException, ClassNotFoundException; writeObject method is responsible for writing the state of the object to the stream readObject method is responsible for reading the state of the object from the stream

22 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

23 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

24 Labs Slide! Let’s do the labs. Lab: Steams

Download ppt "Streams Dwight Deugo ( Nesa Matic ( Portions of the notes for this lecture include excerpts from."

Similar presentations

Ads by Google