streams dwight deugo ([email protected]) nesa matic ([email protected])
TRANSCRIPT
StreamsStreams
Dwight Deugo ([email protected])Dwight Deugo ([email protected])Nesa Matic ([email protected])Nesa Matic ([email protected])
www.espirity.com
2 © 2003-2004, Espirity Inc.
Additional Contributors
None as of September, 2004
3 © 2003-2004, Espirity Inc.
Module Overview
1. Streams
4 © 2003-2004, Espirity Inc.
Module Road Map
1. Streams What are streams? Stream types Character streams Byte streams Filter streams Object Serialization
5 © 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
6 © 2003-2004, Espirity Inc.
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
7 © 2003-2004, Espirity Inc.
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 © 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 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
9 © 2003-2004, Espirity Inc.
Character Streams Hierarchy
Object
OutputStreamWriter
InputStreamReader
<<abstract>>
Writer<<abstract>>
Reader
FileWriterFileReader BufferedWriter
BufferedReader
10 © 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 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 © 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
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
12 © 2003-2004, Espirity Inc.
Writing and Reading Example Create a file
Read the file
FileWriter writefile = new FileWriter("source.txt");
writefile.write('A');
writefile.write("bcdefghi");
writefile.close();
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();
myString
13 © 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 inefficientBufferedReader reader
= new BufferedReader(new DataInputStream(System.in));
String input;
while ((input = reader.readLine()) != null) {
... //do something interesting here
}
14 © 2003-2004, Espirity Inc.
Byte Streams HierarchyInputStrea
m
FileInputStream
FilterInputStream
DataInputStream
BufferdInputStream
ObjectInputStream
Filter streams Object streamsFilter streamsOuputStrea
m
FileOutputStream
FilterOutputStream
DataOutputStream
BufferdOutputStream
ObjectOutputStream
PrintStream
15 © 2003-2004, Espirity Inc.
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 © 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
17 © 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);
double price= inputStream.readDouble();
inputStream.close();
It’s importantto know what’s in the stream
18 © 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);
outputStream.flush();
outputStream.close();
Forces data to be written
19 © 2003-2004, Espirity Inc.
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);}
20 © 2003-2004, Espirity Inc.
Object Serialization Supported with ObjectOutputStream
class Serialized object class must implement the
Serializable interfaceGregorianCalendar 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{…
21 © 2003-2004, Espirity Inc.
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(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
22 © 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
23 © 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
24 © 2003-2004, Espirity Inc.
Labs Slide!
Lab: Steams