Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

70
Prepared By E. Musa Alyam an 1 Data Streams Chapter 4
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    217
  • download

    0

Transcript of Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Page 1: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman1

Data Streams

Chapter 4

Page 2: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman2

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

Page 3: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman3

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

Page 4: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman4

Streams

Streams are divided into 2 categories– Input streams – read from– Output streams – written to

Page 5: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman5

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

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

Page 6: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman6

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

Page 7: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman7

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 fileInputStream 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);}

}

}

Example

Page 8: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman8

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

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

Page 9: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman9

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)

Page 10: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman10

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 inputInputStream input = new FileInputStream( source );

System.out.println ("Opened " + source + " for reading.");

OutputStream output = new FileOutputStream ( destination ); // Ouput output file for output

System.out.println ("Opened " + destination + " for writing.");

int data = input.read();while ( data != -1){

// Write byte of data to our fileoutput.write (data);// Read next bytedata=input.read();

}// Close both streamsinput.close();output.close();

System.out.println ("I/O streams closed");}catch (IOException ioe){

System.err.println ("I/O error - " + ioe);}

}

}

Example

Page 11: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman11

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

Page 12: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman12

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)

Page 13: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman13

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”);

Page 14: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman14

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

Page 15: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman15

Useful Filter Input Streams

Filter Input Stream Purpose of Stream

BufferedInputStream 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

Page 16: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman16

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)

Page 17: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman17

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

Page 18: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman18

DataInputStream Class• Constructor

DataInputStream( InputStream input)

• MethodsBoolean 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 input)

int skipBytes(int number).

Page 19: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman19

LineNumberInputStream Class

• Provides helpful funtionality by tracking the number of lines read from the input stream

• ConstructorsLineNumberInputStream(InputStream input) – creates a

line number stream, reading from the specified input stream

• Methodsint 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

Page 20: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman20

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

Page 21: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman21

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

Page 22: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman22

Filter Output Streams

Filter Output Stream Purpose of Stream

BufferedOutputStream 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

Page 23: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman23

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

• MethodsNo extra methods have been added to this class

Page 24: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman24

DataOutputStream Class• Designed to deal with primitive datatypes such as number or bytes• Constructors

– DataOutputStream(OutputStream output) – creates a data output stream• Methods

– 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

Page 25: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman25

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

• ConstructorsPrintStream(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

Page 26: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman26

PrintStream Class• Methods

– 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”

Page 27: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman27

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

Page 28: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman28

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.

Page 29: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman29

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

Page 30: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman30

Low-level ReadersLow-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 Bridges the divide between an input stream and a reader, by reading from the input stream

Page 31: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman31

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

• MethodsNo new methods

Page 32: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman32

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

• MethodsNo new methods

Page 33: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman33

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

• Methodsvoid connect(PipedWriter writer) – connect the reader to the

specified writer

Page 34: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman34

StringReader Class

• Accepts a string as an input source

• ConstructorsStringReader(String stringToBeRead) – reads from

the beginning of the specified string until the end

• MethodsNo additional methods are added

Page 35: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman35

InputStreamReader Class

• Offers backward compatibility with older input streams

• ConstructorsInputStreamReader(InputStream input) – connects

an input stream to the readerInputStreamReader(InputStream input, String

encoding) – connects an input stream to the reader using the specified encoding form

• MethodsString getEncoding( ) – returns the name of the

character encoding used by the

Page 36: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman36

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 inputInputStream input = System.in;// Create an InputStreamReaderInputStreamReader reader = new InputStreamReader ( input );// Connect to a buffered reader, to use the readLine() methodBufferedReader 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);}

}}

Page 37: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman37

Filter Readers

• Provides additional functionality in the form of new methods or process data in a different way

• Always connect to another reader

Page 38: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman38

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

Page 39: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman39

BufferedReader

• Alternative for better performance to avoid blocking I/O

• ConstructorsBufferedReader(Reader reader) – reads data from

the specified reader into a bufferBufferedReader(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

Page 40: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman40

FilterReader

• Acts as a template on which other filters can be constructed

Page 41: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman41

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

• Methodsvoid unread(int character) – pushes the character back to

the beginning of the queuevoid unread(char[] charArray) – pushes every character

in the specified array into the queuevoid unread(char[] charArray, int offset, int length) –

pushes a subset of the character in the specified array into the queue

Page 42: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman42

LineNumberReader

• Provides a useful line counter that measures how many lines have been read

• ConstructorsLineNumberReader(Reader reader) – creates a new line-

number readerLineNumberReader(Reader reader, int size) – creates a

new line-number reader and allocated a buffer of the specified size

• Methodsint getLineNumber( ) – returns the current line numbervoid setLineNumber(int lineNumber) – modifies the line-

number counter

Page 43: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman43

Output Streams to Writers

• An equivalent class to java.io.OutputStream

• Has similar method signatures and supports Unicode characters

Page 44: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman44

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

Page 45: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman45

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

• Methodschar[ ] toCharArray – returns a character array,

containing all characters written

String toString( ) – returns a string containing all characters

Page 46: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman46

FileWriter Class

• Provides a convenient way to write characters to a local file

• ConstructorsFileWriter(File file) – creates a writer connected to the

resource represented by the specified file objectFileWriter(FileDescriptor) – creates a writer connected to

the specified descriptor handleFileWriter(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

Page 47: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman47

PipedWriter Class

• Use to write data that will be read by PipedReader

• ConstructorsPipedWriter( ) – creates an unconnected pipe writer

PipedWriter(PipedReader reader) – creates a piped writer connected to the specified reader

• Methodsvoid connect(PipedReader reader) – attempts to

connect to the specified reader

Page 48: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman48

StringWriter Class• Maintains a string buffer and provides a method

to access the buffer contents or to convert to a string

• ConstructorsStringWriter( ) – creates a new string writer

StringWriter(int startingSize) – creates a new string writer and allocates a StringBuffer of the specified size

• MethodsStringBuffer getBuffer( ) – returns the buffer used to

store data sent to the writer

String toString( ) – converts the internal buffer into a string

Page 49: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman49

OutputStreamWriter Class

• Handles the translation between a Writer and an OutputStream allowing new writer to interact with older output streams

• ConstructorsOutputStreamWriter(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

Page 50: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman50

OutputStreamWriter Exampleimport java.io.*;public class OutputStreamToWriterDemo {

public static void main(String args[]){

try{

//Get the output stream representing standard outputOutputStream output = System.out;// Create an OutputStreamWriterOutputStreamWriter writer = new OutputStreamWriter (output);// Write to standard output using a writerwriter.write ("Hello world");// Flush and writer, to ensure it is writtenwriter.flush(); writer.close();

}catch (IOException ioe){

System.err.println ("I/O error : " + ioe);}

}}

Page 51: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman51

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

Page 52: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman52

BufferedWriter Class

• Used to improve system performance by buffering write request together

• ConstructorsBufferedWriter(Writer writer) – creates a buffered

writer connected to the specified writer

BufferedWriter(Writer writer, int bufferSize) – creates a buffered writer with the specified size

• MethodsNo new methods

Page 53: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman53

FilterWriter Class

• Offer no additional functionality but may be used as a template

• ConstructorsProtected FilterWriter(Writer writer) – creates a filter

writer instance

• MethodsNo new method

Page 54: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman54

PrintWriter Class

• Provides methods for writing datatypes as text

• ConstructorsPrintWriter(Writer writer) – creates a print writer,

writing to the specified writerPrintWriter(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

• MethodsThe same as PrintStream class

Page 55: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman55

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?

Page 56: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman56

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

Page 57: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman57

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

Page 58: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman58

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

Page 59: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman59

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

Page 60: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman60

Graphs

Vector

Object i Object n

OutputStream

1010100101

Page 61: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman61

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

Page 62: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman62

Example

Public class SomeClass extends SomeOtherClass implements java.io.Serializable {

public class SomeClass()

}

}

………

}

Page 63: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman63

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

Page 64: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman64

Example

Public class UserAccount implements java.io.Serializable {

protected String username;protected transient String password;

public UserAccount( ){

….}

}

Page 65: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman65

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

Page 66: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman66

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

Page 67: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman67

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

Page 68: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman68

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

Page 69: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman69

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

Page 70: Prepared By E. Musa Alyaman1 Data Streams Chapter 4.

Prepared By E. Musa Alyaman70

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