11-Streams.v2.0.0

Download Report

Transcript 11-Streams.v2.0.0

www.espirity.com
Streams
Dwight Deugo ([email protected])
Nesa Matic ([email protected])
Additional Contributors

None as of September, 2004
2
© 2003-2004, Espirity Inc.
Module Overview
1. Streams
3
© 2003-2004, Espirity Inc.
Module Road Map
1. Streams






What are streams?
Stream types
Character streams
Byte streams
Filter streams
Object Serialization
4
© 2003-2004, Espirity Inc.
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
5
© 2003-2004, Espirity Inc.
Stream Concept

To read data serially, a Java program:

Opens a stream to a data source






Reads the information serially
To write data serially, a Java program:


file
remote socket
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
6
© 2003-2004, Espirity Inc.
Stream Types

Two different types of streams:

Character streams




Byte streams




Support reading and writing of characters, text
Contain 16-bit Unicode characters
Supported through Reader and Writer classes
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
7
© 2003-2004, Espirity Inc.
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 8bit 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
8
© 2003-2004, Espirity Inc.
Character Streams Hierarchy
Object
InputStream
Reader
OutputStream
Writer
<<abstract>>
<<abstract>>
Reader
Writer
FileReader
BufferedReader
FileWriter
9
BufferedWriter
© 2003-2004, Espirity Inc.
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
int
int
int
int
int
read()
read(char buffer[])
read(char buffer[], int offset, int length)
write(int aCharacter)
write(char buffer[])
write(char buffer[], int offset, int length)
10
© 2003-2004, Espirity Inc.
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
It’s important to
close the stream
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();
11
© 2003-2004, Espirity Inc.
Writing and Reading Example

Create a file
FileWriter writefile = new FileWriter("source.txt");
writefile.write('A');
writefile.write("bcdefghi");
writefile.close();

myString
Abcdefghi
Read the file
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();
12
© 2003-2004, Espirity Inc.
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
}
13
© 2003-2004, Espirity Inc.
Byte Streams Hierarchy
InputStream
FileInputStream
FilterInputStream
DataInputStream
Filter streams
ObjectInputStream
BufferdInputStream
Filter streams
Object streams
OuputStream
FileOutputStream
DataOutputStream
FilterOutputStream
BufferdOutputStream
14
ObjectOutputStream
PrintStream
© 2003-2004, Espirity Inc.
Specialized Byte Streams

File streams


Object streams



Used for writing data to files and reading data from files
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
15
© 2003-2004, Espirity Inc.
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
16
© 2003-2004, Espirity Inc.
Using Filter Streams…

For reading primitive data types

DataInputStream class can be used
FileInputStream inputFile =
new FileInputStream("price.cat");
DataInputStream inputStream =
new DataInputStream(inputFile);
It’s important
to know what’s
in the stream
double price= inputStream.readDouble();
inputStream.close();
17
© 2003-2004, Espirity Inc.
…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);
Forces data
to be written
outputStream.flush();
outputStream.close();
18
© 2003-2004, Espirity Inc.
Streams in System Class

System.in - standard input



System.out - standard output



An instance of BufferedInputStream class
Used to read lines of text that user enters
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);}
19
© 2003-2004, Espirity Inc.
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();
public class java.util.GregorianCalendar extents
java.util.Calendar{…
public class java.util. GregorianCalendar extents
java.lang.Object implements java.lang.Cloneable,
java.io.Serializable{…
20
© 2003-2004, Espirity Inc.
Serialization Protocol

Classes that perform serialization and
deserialization must implement special methods:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;


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
21
© 2003-2004, Espirity Inc.
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
22
© 2003-2004, Espirity Inc.
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
23
© 2003-2004, Espirity Inc.
Labs Slide!
Lab: Steams
24
© 2003-2004, Espirity Inc.