Data Streams
Download
Report
Transcript Data Streams
Chapter 4
Data Streams
1
Prepared By E. Musa Alyaman
Overview
• Communication over networks with files
and even between applications is
represented in Java by streams
• Stream-based communication is central to
almost any type of Java application
• This concept is important when dealing
with networking applications
2
Prepared By E. Musa Alyaman
Streams
• Byte-level communication is represented in Java
by streams which information is sent and
received
• Imagine a water pipe – properly installed so that
water that goes in one end comes out the other
• When designing a system, the correct stream
must be selected
• Streams may be chained together to provide an
easier and more manageable interface
3
Prepared By E. Musa Alyaman
Streams
Streams are divided into 2 categories
– Input streams – read from
– Output streams – written to
4
Prepared By E. Musa Alyaman
Reading from an Input Stream
• Many input streams
are provided by the
java.io package
• When a low-level
input stream is
created, it will read
from a source of
information that
supplied it with data
• Inputs streams act
as consumers of
information
5
Low-level Input Stream Purpose of Stream
byteArrayInputStream
Reads bytes of data
from an in-memory
array
FileInputStream
Reads bytes of data
from a file on the
local file system
PipedInputStream
Reads bytes of data
from a thread pipe
StringBufferInputStream
Reads bytes of data
from a string
SequenceInputStream
Reads bytes of data
from one or more
low-level streams
System.in
Reads bytes of data
from the user
console
Prepared By E. Musa Alyaman
The java.io.InputStream Class
• The abstract InputStream class defines methods common to
all input streams and all of them are public
• Methods
–
–
–
–
–
–
–
int available ( ) throws java.io.IOException
void close ( ) throws java.io.IOException
void mark(int readLimit)
boolean markSupported ( )
int read( ) throws java.io.IOException
int read(byte[ ] byteArray) throws java.io.IOException
int read(byte [ ] byteArray, int offset, int length) throws
java.io.IOException, java.lang.IndexOutOfBoundsException
– void reset( ) throws java.io.IOException
– long skip(long amount) throws java.io.IOException
6
Prepared By E. Musa Alyaman
Example
import java.io.*;
public class FileInputStreamDemo
{
public static void main(String args[])
{
if (args.length != 1)
{
System.err.println ("Syntax - FileInputStreamDemo file");
return;
}
try
{
// Create an input stream, reading from the specified file
InputStream fileInput = new FileInputStream ( args[0] );
int data = fileInput.read(); // Read the first byte of data
while (data != -1) // Repeat : until end of file (EOF) reached
{
System.out.write ( data ); // Send byte to standard output
data = fileInput.read(); // Read next byte
}
fileInput.close(); // Close the file
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
7
Prepared By E. Musa Alyaman
Writing to an Output Stream
• A number of output streams
are available for a variety of
tasks. I.e. writing to data
structures including strings and
arrays or to files or
communication pipes
• An output stream is a data
producer. It creates bytes of
information and transmit them
to something else
• Data is communicated
sequentially, the first byte in
will be the first byte out
8
Low-Level Output
Stream
Purpose of Stream
ByteArrayOutputStream
Writes bytes of data
to an array of bytes
FileOutputStream
Writes bytes of data
to a local file
PipedOutputStream
Writes bytes of data
to a communications
pipe
StringBufferOutputStream Writes bytes to a
string buffer
System.err
Writes bytes of data
to the error stream of
the user console
System.out
Writes bytes of data
to the user console
Prepared By E. Musa Alyaman
The java.io.OutputStream Class
• Methods
– Void close( )
– Void flush( )
– Void write(int byte)
– Void write(byte[ ] byteArray)
– Void write(byte[ ] byteArray, int offset, int length)
(NB: All of these methods throws java.io.IOException)
9
Prepared By E. Musa Alyaman
Example
import java.io.*;
public class FileOutputStreamDemo
{
public static void main(String args[])
{
if (args.length != 2)
// Two parameters are required, the source and destination
{
System.err.println ("Syntax - FileOutputStreamDemo src dest");
return;
}
String source = args[0];
String destination = args[1];
try
{
// Open source file for input
InputStream input = new FileInputStream( source );
System.out.println ("Opened " + source + " for reading.");
OutputStream output = new FileOutputStream ( destination );
System.out.println ("Opened " + destination + " for writing.");
int data = input.read();
while ( data != -1)
{
// Write byte of data to our file
output.write (data);
// Read next byte
data=input.read();
}
// Close both streams
input.close();
output.close();
System.out.println ("I/O streams closed");
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
10
}
Prepared By E. Musa Alyaman
// Ouput output file for output
Filter Streams
• Basic low-level streams provide a simple
mechanism to read and write bytes of
information
• However, their flexibility is limited
• Reading bytes is complex process as
compared to other forms of information
like text, number etc.
• Byte-level communication can also be
inefficient if buffering is not used
11
Prepared By E. Musa Alyaman
Filter Streams
• Filter streams add additional functionality
to an existing stream
• They process data in some form (such as
buffering for performance) or offers
additional methods that allow data to be
accessed in different manner (i.e. reading
a line of text rather than sequence of
bytes)
12
Prepared By E. Musa Alyaman
Connecting a Filter Stream to an Existing Stream
• Suppose we want to connect a
PrintStream (to print text to an
OutputStream subclass) to a stream that
wrote to a file.
FileOutputStream fout = FileOutputStream (somefile);
PrintStream pout = new PrintStream(fout);
Pout.println (“Hello world”);
13
Prepared By E. Musa Alyaman
Connecting a Filter Stream to an Existing Stream
•
The process is simple as long as the
programmer remember two things:
1. Read and write operations must take place
on the new filter stream
2. Read and write operations on the underlying
stream can still take place, but not at the
same time as an operation on the filter
stream
14
Prepared By E. Musa Alyaman
Useful Filter Input Streams
Filter Input Stream
BufferedInputStream
Purpose of Stream
Buffers access to data, to
improve efficiency
DataInputStream
Reads primitive data types,
(int, float, double etc)
LineNumberInputStream
Maintains a count of which
line is being read, based on
interpretation of end-of-line
characters
PushBackInputStream
Allows a byte of data to be
pushed into the head of the
stream
15
Prepared By E.
Musa Alyaman
BufferedInputStream Class
•
•
•
•
•
•
The purpose of I/O buffering is to improve
system performance
Reading a large number of bytes not a byte at
a time
When read( ) method is invoked
Reading subsequent bytes from buffer not the
underlying input stream
Improves data access time and can reduce the
number of times an application blocks for input.
Constructors:
1. BufferedInputStream(inputStream input)
2. BufferedInputStream(InputStream input, int bufferSize)
16
Prepared By E. Musa Alyaman
DataInputStream Class
• A frequent task is any programming
language is reading and writing primitives
data types such as number and characters
• These information is not easily
represented as bytes
• Developers can avoid worrying this
problem by invoking methods of
DataInputStream class that handles
translations automatically
17
Prepared By E. Musa Alyaman
• Constructor
DataInputStream Class
DataInputStream( InputStream input)
• Methods
18
Boolean readBoolean( )
Byte readByte( )
char readChar( )
double readDouble( )
float readFloat( )
void readFully(byte[ ] byteArray)
void readFully(byte[] byteArray, int offset, int length)
float readInt( )
string readLine( )
long readLong( )
short readShort( )
int readUnsignedByte( )
int readUnsignedShort( )
String readUTF( )
Static String readUTF(DataInputStream
Prepared By E. Musa input)
Alyaman
int skipBytes(int number).
LineNumberInputStream Class
• Provides helpful funtionality by tracking the
number of lines read from the input stream
• Constructors
LineNumberInputStream(InputStream input) – creates a
line number stream, reading from the specified input
stream
• Methods
int getLineNumber( ) – returns the number of lines that
have been read by this input stream
void setLineNumber(int number) – modifies the line
number counter to the specified value
19
Prepared By E. Musa Alyaman
PushBackInputStream Class
• Allows a single byte to be read and then
pushed back into the stream for later
reading
• An internal buffer is maintained that allows
data to be pushed back into the front of
the input stream buffer
• Useful if the programmer want to “sneak
peek” at what is coming – for example, in
a text parser or to determine what the next
command in a communication protocol is
going
to
be
20
Prepared By E. Musa Alyaman
PushBackInputStream Class
• Constructor
– PushBackInputStream(InputStream input) – creates a
PushBackInputStream that will read from the specified input
stream
– PushBackInputStream(InputStream input, int bufferSize) –
creates a PushBackInputStream that will read from an input
stream and use a buffer of the specified size
• Methods
– void unread(byte[] byteArray) – pushes back the contents of
the specified array. If a buffer overrun occurs, an exception is
thrown
– void unread(byte[] byteArray, int offset, int length) – pushes
back a subset of the contents of the specified array
– void unread(int byte) – pushes back the specified byte into the
front of the buffer
21
Prepared By E. Musa Alyaman
Filter Output Streams
Filter Output Stream
BufferedOutputStream
Purpose of Stream
Provides buffering of data
writes, to improve
efficiency
DataOutputStream
Writes primitive datatype
such as bytes and
numbers
PrintStream
Offers additional methods
for writing lines of text and
other
datatypes as text
22
Prepared By E. Musa
Alyaman
BufferedOutputStream Class
• An internal buffer is maintained and when the buffer is
complete (or earlier, if request to flush the buffer is
made), the buffer contents are dumped to the output
stream to which the buffered stream is connected
• Constructors
– BufferedOutputStream(OutputStream output) – creates a buffer
for writing to the specified output stream. (default buffer size is
512 bytes)
– BufferedOutputStream(OutputStream output, int bufferSize) –
creates a buffer for writing to the specified output stream,
overriding the default buffer sizing
• Methods
No extra methods have been added to this class
23
Prepared By E. Musa Alyaman
DataOutputStream Class
•
•
Designed to deal with primitive datatypes such as number or bytes
Constructors
–
•
Methods
–
–
–
–
–
–
–
–
–
–
–
–
24
DataOutputStream(OutputStream output) – creates a data output stream
int size( ) – returns the number of bytes written to the data output stream
void writeBoolean(boolean value) – writes the specified boolean value, represented as a
one-byte value
void writeByte(int byte) – writes the specified byte to the output stream
void writeBytes(String string) – writes the entire contents of a string to the output stream a
byte at a time
void writeChar(int char) – writes the character to the output stream as a two-byte value
void writeChars(String string) – writes the entire contents of a string to the output stream,
represented as two-byte valuesMethods
void writeDouble(double doubleValue) – converts the specified double value to a long value
and then converts it to an eight-byte value
void writeFloat(float floatValue) – converts the specified float value to an int and then writes it
as a four-byte value
void writeInt(int intValue) – writes an int value as a four-byte value
void writeLong(int intValue) – writes a long value as eight bytes
void writeShort(int intValue) – writes a short value as two bytes
void writeUTF(String string) – writes a string using UTF-8 encoding
Prepared By E. Musa Alyaman
PrintStream Class
• Provides a convenient way to print primitives
datatypes as text using the print(..) method and
to print these with line separators using the
println(..) method
• Constructors
PrintStream(OutputStream output) – creates a print
stream for printing of datatypes as text
PrintStream(OutputStream output, boolean flush) –
creates a print stream for printing of datatypes as text.
If the boolean is set to “true”, the underlying buffer will
be automatically flushed
25
Prepared By E. Musa Alyaman
PrintStream Class
•
Methods
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
26
boolean checkError( ) – automatically flushed the output stream and checks to see if an error has occurred
void print(boolean value) – print a boolean value
void print(char character) – prints a character value
void print(char [] charArray) – prints an array of characters
void print(double doubleValue) – prints a double value
void print(float floatValue) – prints a float value
void print(int intValue) – prints an int value
void print(long longValue) – prints a long value
void print(Object obj) – prints the value of the specified object’s toString( ) method
void print(String string) – prints a string’s contents
void println( ) – sends a line separator (\n)
void println(char character) – prints a character value followed by a println()
void println(char[] charArray) – prints an array of characters followed by println()
void println(double doubleValue) – prints a double value followed by println() Methods
void println(float floatValue) – prints a float value followed by println()
void println(int intValue) – prints an int value followed by println()
void println(long longValue) – prints a long value followed by println()
void println(Object obj) – prints the value of the specified object’s toString( ) method followed by println()
void println(String string) – prints a string followed by a line separator
protected void SetError( ) – modifies the error flag to a value of “true”
Prepared By E. Musa Alyaman
Readers and Writers
• Better options to support Unicode
character streams
• Better alternative when used on text data
• Unicode has a maximum of 65536
possible characters compared to just 255
in ASCII
27
Prepared By E. Musa Alyaman
Readers and Writers
• The most important subclasses of Reader and Writer
are
the
InputStreamReader
and
OutputStreamWriter.
• InputStreamReader contains an underlying input
stream form which it reads raw bytes. It translates
these bytes into Unicode characters according to
specific encoding.
• OutputStreamWriter receives Unicode characters
from a running program. It translates those characters
into bytes using a specified encoding and writes the
bytes onto an underlying output stream.
28
Prepared By E. Musa Alyaman
Input Stream to Readers
• Java.io.Reader class is a character-based
equivalent as java.io.InputStream class
• Similar method signatures with slight
changes to support character reading
• Method available( ) is removed and
replaced by ready( ) method
29
Prepared By E. Musa Alyaman
Low-level Readers
Low-Level Reader
Purpose of Reader
CharArrayReader
Reads from a character array
FileReader
Reads from a file on the local
system, just like a
FileInputStream
PipedReader
Reads a sequence of
characters from a thread of
communications pipe
StringReader
Reads a sequence of
characters from a String
InputStreamReader
30
Bridges the divide between an
input stream and a reader, by
Prepared By E. Musa Alyaman
reading from the input stream
CharArrayReader Class
• A reader that obtains data by reading characters
from an array
• Constructors
– CharArrayReader(char[ ] charArray) – creates a
character array reader that will operate on the
specified array
– charArrayReader(char[ ] charArray, int offset, int
length) – creates a character array reader that will
operate only on a subset of the specified array
• Methods
No new methods
31
Prepared By E. Musa Alyaman
FileReader Class
• Obtains its data directly from a local file
• Constructors
–
FileReader(File file) – creates a reader that will access the
contents of the specified file object, if the file exists
– FileReader(String filename) – creates a reader that will access
the contents of the specified filename, if it exists
– FileReader(FileDescriptor descriptor) – creates a reader that
will access the contents of the specified descriptor handle
• Methods
No new methods
32
Prepared By E. Musa Alyaman
PipedReader Class
• Used to establish a pipe between one
thread and another
• Constructors
– PipedReader( ) – creates an unconnected pipe reader
– PipedReader(PipedWriter writer) – creates a connected pipe
that will read the output of the specified writer
• Methods
void connect(PipedWriter writer) – connect the reader to the
specified writer
33
Prepared By E. Musa Alyaman
StringReader Class
• Accepts a string as an input source
• Constructors
StringReader(String stringToBeRead) – reads from
the beginning of the specified string until the end
• Methods
No additional methods are added
34
Prepared By E. Musa Alyaman
InputStreamReader Class
• Offers backward compatibility with older
input streams
• Constructors
InputStreamReader(InputStream input) – connects
an input stream to the reader
InputStreamReader(InputStream input, String
encoding) – connects an input stream to the reader
using the specified encoding form
• Methods
String getEncoding( ) – returns the name of the
character encoding used by the
35
Prepared By E. Musa Alyaman
Combining Streams and Readers (example)
import java.io.*;
public class InputStreamToReaderDemo
{
public static void main(String args[])
{
try
{
System.out.print ("Please enter your name : ");
// Get the input stream representing standard input
InputStream input = System.in;
// Create an InputStreamReader
InputStreamReader reader = new InputStreamReader ( input );
// Connect to a buffered reader, to use the readLine() method
BufferedReader bufReader = new BufferedReader ( reader );
String name = bufReader.readLine();
System.out.println ("Pleased to meet you, " + name);
}
catch (IOException ioe)
{
System.err.println ("I/O error : " + ioe);
}
}
}
36
Prepared By E. Musa Alyaman
Filter Readers
• Provides additional functionality in the
form of new methods or process data in a
different way
• Always connect to another reader
37
Prepared By E. Musa Alyaman
Filter Readers
Filter Reader
Purpose of Stream
BufferedReader
Buffers access to data, to
improve efficiency
FilterReader
Provides a class to entend
when creating filters
PushBackReader
Allows text data to be pushed
back into the reader’s stream
LineNumberReader
Buffered reader subclass which
maintains a count of which line
it is on
38
Prepared By E. Musa Alyaman
BufferedReader
• Alternative for better performance to avoid
blocking I/O
• Constructors
BufferedReader(Reader reader) – reads data from
the specified reader into a buffer
BufferedReader(Reader reader, int bufferSize) –
reads data from the specified reader into a buffer
which is allocated to the specified size
• Methods
String readLine( ) – read a line of text from the
underlying stream
39
Prepared By E. Musa Alyaman
FilterReader
• Acts as a template on which other filters
can be constructed
40
Prepared By E. Musa Alyaman
PushBackReader
• Allows characters to be pushed back into the
head of a reader’s input queue
• Constructors
PushBackReader(Reader reader) –creates a push-back
reader with a single character buffer
PushBackReader(Reader reader, int bufferSize) –
creates a push-back reader with a larger buffer of
specified size
• Methods
void unread(int character) – pushes the character back to
the beginning of the queue
void unread(char[] charArray) – pushes every character
in the specified array into the queue
void unread(char[] charArray, int offset, int length) –
pushes a subset of the character in the specified array
into the queue
41
Prepared By E. Musa Alyaman
LineNumberReader
• Provides a useful line counter that measures
how many lines have been read
• Constructors
LineNumberReader(Reader reader) – creates a new linenumber reader
LineNumberReader(Reader reader, int size) – creates a
new line-number reader and allocated a buffer of the
specified size
• Methods
int getLineNumber( ) – returns the current line number
void setLineNumber(int lineNumber) – modifies the linenumber counter
42
Prepared By E. Musa Alyaman
Output Streams to Writers
• An equivalent class to
java.io.OutputStream
• Has similar method signatures and
supports Unicode characters
43
Prepared By E. Musa Alyaman
Types of low-level Writers
Low-Level Writer
Purpose of Writer
CharArrayWriter
Writes to a variable length
character array
FileWriter
Writes to a file on the local file
system
PipedWriter
Writes characters to a thread
communications pipe
StringWriter
Writes characters to a string
buffer
OutputStreamWriter
Writes to a legacy output
stream
44
Prepared By E. Musa Alyaman
CharArrayWriter Class
• Maintains an internal buffer that is added to each
time write request is made
• Constructors
CharArrayWriter( ) – creates a character writer that can
be converted to a character array
CharArrayWriter(int bufferSize) – creates a character
array writer using the specified initial buffer size
• Methods
char[ ] toCharArray – returns a character array,
containing all characters written
String toString( ) – returns a string containing all
characters
45
Prepared By E. Musa Alyaman
FileWriter Class
• Provides a convenient way to write characters to
a local file
• Constructors
FileWriter(File file) – creates a writer connected to the
resource represented by the specified file object
FileWriter(FileDescriptor) – creates a writer connected to
the specified descriptor handle
FileWriter(String filename) – writes to the specified file
location file location, creating if not exist or overwrite an
existing file
FileWriter(String filename, boolean appendFlag) – writes
to the specified file location. If the appendFlag is “true”,
file will be opened in append mode
46
Prepared By E. Musa Alyaman
PipedWriter Class
• Use to write data that will be read by
PipedReader
• Constructors
PipedWriter( ) – creates an unconnected pipe writer
PipedWriter(PipedReader reader) – creates a piped
writer connected to the specified reader
• Methods
void connect(PipedReader reader) – attempts to
connect to the specified reader
47
Prepared By E. Musa Alyaman
StringWriter Class
• Maintains a string buffer and provides a method
to access the buffer contents or to convert to a
string
• Constructors
StringWriter( ) – creates a new string writer
StringWriter(int startingSize) – creates a new string
writer and allocates a StringBuffer of the specified size
• Methods
StringBuffer getBuffer( ) – returns the buffer used to
store data sent to the writer
String toString( ) – converts the internal buffer into a
string
48
Prepared By E. Musa Alyaman
OutputStreamWriter Class
• Handles the translation between a Writer
and an OutputStream allowing new writer
to interact with older output streams
• Constructors
OutputStreamWriter(OutputStream output) – creates
a writer that will translate between characters and
bytes using default character encoding
OutputStreamWriter(OutputStream output, String
encoding) – creates a writer that translates
between characters and bytes using the specified
character encoding
49
Prepared By E. Musa Alyaman
OutputStreamWriter Example
import java.io.*;
public class OutputStreamToWriterDemo
{
public static void main(String args[])
{
try
{
//Get the output stream representing standard output
OutputStream output = System.out;
// Create an OutputStreamWriter
OutputStreamWriter writer = new OutputStreamWriter (output);
// Write to standard output using a writer
writer.write ("Hello world");
// Flush and writer, to ensure it is written
writer.flush(); writer.close();
}
catch (IOException ioe)
{
System.err.println ("I/O error : " + ioe);
}
}
}
50
Prepared By E. Musa Alyaman
Types of Filtered Writers
Filter Writer
Purpose of Writer
BufferedWriter
Buffers write requests
FilterWriter
Abstract class for developing
filter writers
PrintWriter
Provides convenient
PrintStream-like functionality
51
Prepared By E. Musa Alyaman
BufferedWriter Class
• Used to improve system performance by
buffering write request together
• Constructors
BufferedWriter(Writer writer) – creates a buffered
writer connected to the specified writer
BufferedWriter(Writer writer, int bufferSize) – creates
a buffered writer with the specified size
• Methods
No new methods
52
Prepared By E. Musa Alyaman
FilterWriter Class
• Offer no additional functionality but may be
used as a template
• Constructors
Protected FilterWriter(Writer writer) – creates a filter
writer instance
• Methods
No new method
53
Prepared By E. Musa Alyaman
PrintWriter Class
• Provides methods for writing datatypes as
text
• Constructors
PrintWriter(Writer writer) – creates a print writer,
writing to the specified writer
PrintWriter(Writer writer, boolean flushFlag) –
creates a print writer that will be flushed depending
on the boolean value. If “true”, it will flush when
println method is executed
• Methods
The same as PrintStream class
54
Prepared By E. Musa Alyaman
Object Persistence and Object serialization
• Data can be read or written ranges from
individual bytes to primitives datatypes and
string
• We can write a data structure (such as a
sequence of a data records, composed of
individual fields) out of a file.
• How about if we wanted to store an entire
object?
55
Prepared By E. Musa Alyaman
Object Persistence and Object serialization
• This requires each field of the object be written
individually; then at later time, each field would
be read back and assigned to an object
• A complicated process!
• Since saving data is one of the most important
functions of software
• The solution is to use object persistence
56
Prepared By E. Musa Alyaman
What is object persistence
• The ability of an object to persist over time (if
moved to a different machine, over space)
• Most objects in Java Virtual Machine are fairly
short-lived
• When there is no reference to the object, the
memory space allocated to it is reclaimed by the
automatic garbage collector thread
• All object will die at some point in time resulted
loss reference
57
Prepared By E. Musa Alyaman
Object Serialization
• The technique by which object persistence is
realized
• It controls how the data that comprises an
object’s state information (the individual member
variables, whether public, private or protected) is
written as a sequence of bytes
• The serialized object might be sent over the
network or saved to a disk so that it can be
accessed at some point in the future
• This allows objects to move from one JVM to
another whether located on the same machine
or a remote one
58
Prepared By E. Musa Alyaman
Object Serialization
• Serialization works by examining the variables of
an object and writing primitives datatypes like
numbers and characters to a byte stream
• It also caters a situation where an object is
inside another object.
• if an object has a reference to an object which
has a reference to another object, they are all
saved together
• The set of all objects referenced is called a
graph of objects and object serialization
converts entire graphs to byte form
59
Prepared By E. Musa Alyaman
Graphs
1010100101
Vector
OutputStream
Object i
60
…
Object n
Prepared By E. Musa Alyaman
How serialization works
• Any object that implements the java.io.Serializable
interface may be serialized with only a few lines of code
• Implementing the java.io.Serializable interface requires
no additional effort on the part of developers, other than
adding the appropriate “implements” statement during
the class declaration and declaring a no-argument
constructor
• The interface acts as an indication that the developer
endorses serialization – no method needs to be
implemented to support serialization
61
Prepared By E. Musa Alyaman
Example
Public class SomeClass extends
SomeOtherClass implements
java.io.Serializable {
public class SomeClass()
}
}
………
}
62
Prepared By E. Musa Alyaman
Issues
• Legitimate reasons for not supporting
serialization also exist
• For example, if an object contained very
sensitive information it might be unwise to
serialize it and save it to disk or send it over the
a network
• Suppose a class stored password data that can
be easily obtained. To prevent individual
member variables being serialized, they can be
marked with the transient keyword
63
Prepared By E. Musa Alyaman
Example
Public class UserAccount implements
java.io.Serializable {
protected String username;
protected transient String password;
public UserAccount( )
{
….
}
}
64
Prepared By E. Musa Alyaman
Reading and Writing Objects to
Streams
• The main point of serialization is to write an
object out to a stream and to read it back
• This is accomplished by using the
java.io.ObjectOutputStream and
java.io.ObjectInputStream classes
65
Prepared By E. Musa Alyaman
ObjectInputStream Class
• Use to read a serialized object from a byte
stream
• To allow an object to be reconstituted back to its
original form
• The outputInputStream class implements the
ObjectInput interface which extends the
DataInput interface. This mean that this class
provides many method with the same signature
as DataInputStream
66
Prepared By E. Musa Alyaman
ObjectInputStream Class
• Constructors
• Protected ObjectInputStream ( ) – provides a
default constructor for ObjectInputStream
subclasses
• ObjectInputStream( InputStream input) – creates
an object input stream connected to the specified
input stream, capable of restoring serialized
objects
• Methods
• Public final Object readObject( ) – reads a
serialized object from the stream reconstructs it to
its original state
67
Prepared By E. Musa Alyaman
ObjectOutputStream Class
• Serializes an object to a byte stream for
the purpose of object persistence
• May be connected to any existing output
stream such as file or a networking
stream.
• Objects written to an ObjectOutputStream
have all their member variables written
68
Prepared By E. Musa Alyaman
ObjectOutputStream Class
• Constructors
• Protected ObjectOutputStream ( ) – default
constructor
• ObjectOutputStream (OutputStream output) –
creates an object output stream capable of
serializing objects to the specified output stream
• Methods
• Void writeObject (Object object) – writes the
specified object to the output stream through
object serialization
69
Prepared By E. Musa Alyaman
Chapter Highlights
You have learned:
• What streams are and how they work
• What readers and writers are and how they work
• How to connect filter streams to low-level
streams
• How to connect readers and writers to streams
• About object serialization and how to read and
write objects
70
Prepared By E. Musa Alyaman