Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

UNIT 3

INPUT AND OUTPUT

© Ganapathi Nayak K
1
Files and Directories

File
Class present in the package java.io
Deals with files and file system (and not streams)
 Does not specify how information is stored in and retrieved from files
 Describes the properties of the file itself

File object: Obtain and manipulate information associated with a disk file
 Permissions, Time, Date, Directory path etc.

Directory: Treated as a File


A list of filenames

© Ganapathi Nayak K
2
Files and Directories

File (Continued …)
Constructors used to create File objects (new File instances)
File (String directoryPath)
File (String directoryPath, String fileName)
File (File dirObj, String fileName)
File (URI URIObj)

Examples:
File f1 = new File (“/”);
File f2 = new File (“/Dir1”, “sample1.txt”);
File f3 = new File (f1, “sample2.txt”);

Note: Path separators – either / (Unix) or \ (Windows)

© Ganapathi Nayak K
3
Files and Directories

File Methods

Method Description

String getName () File name

String getPath () Relative path

String getAbsolutePath () Absolute path

String getParent () Parent directory name

boolean exists () Exists or not

boolean canWrite () Writeable

boolean canRead () Readable

boolean canExecute () Executable

© Ganapathi Nayak K
4
Files and Directories

File Methods (Continued …)

Method Description

long lastModified () Last modified time

long length () File size

boolean isFile () File (true) or Directory (false)

boolean isDirectory () Directory or not

boolean isAbsolute () Absolute path (true) or Relative path (false)

boolean renameTo (File newName) Rename file; returns true if successful


Example Delete
for File
fileMethods
or directory (if empty);
boolean delete ()
returns true if successful
Creates a new, empty file only if a file with this
boolean createNewFile ()
name does not yet exist.

Example for File Methods

© Ganapathi Nayak K
5
Files and Directories

File Methods (Continued …)

Method Description

Returns the number of bytes of storage available on the


long getFreeSpace ()
partition associated with the invoking object
Returns the storage capacity of the partition associated
long getTotalSpace ()
with the invoking object
Returns the number of usable free bytes of storage
long getUsableSpace () available on the partition associated with the invoking
object
Returns true if the invoking file hidden. Returns false
boolean isHidden ()
otherwise.

Sets the time stamp on the invoking file to that specified by


setLastModified
boolean millsec, which is the number of milliseconds from January
(long millisec)
1, 1970, Coordinated Universal Time (UTC)

© Ganapathi Nayak K
6
Files and Directories

File Methods (Continued …)

Method Description

boolean setReadOnly () Sets the invoking file to read-only

setWritable
boolean (boolean writable, Sets/resets the invoking file to writable
boolean ownerOnly)

setExecutable
boolean (boolean writable, Sets/resets the invoking file to executable
boolean ownerOnly)

© Ganapathi Nayak K
7
Files and Directories

Directories
A File that contains list of other files and directories
Methods available

Method Description

boolean isDirectory () Returns true if it is a directory; otherwise, false

String[] list () List of files and directories in it

Example for Directory List

© Ganapathi Nayak K
8
Files and Directories

Directories (Continued …)
Using FilenameFilter: Select files that match a certain pattern
Syntax: String[] list (FilenameFilter FFObj)
FFObj is an object that implements FilenameFilter interface
FilenameFilter (interface) defines a method accept()
Syntax: boolean accept (File directory, String filename)
Returns true for files in the directory specified by directory to be included in the list (of
files to be filtered)

Example for FilenameFilter

© Ganapathi Nayak K
9
Files and Directories

Directories (Continued …)
The listFiles() alternative
Returns file list as an array of File objects instead of strings
Form 1: File[] listFiles ()
Form 2: File[] listFiles (FilenameFilter FFObj)
Form 3: File[] listFiles (FileFilter FObj)
FileFilter (abstract class) defines only a single method called accept(), which is called
once for each file in the list
boolean accept (File path)
Returns true for files to be included in the list (those which match the path argument);
false for others

Example for FileFilter

© Ganapathi Nayak K
10
Files and Directories

Creating Directories
The mkdir() method
 Createsa directory; returns true on success, false on failure
Syntax: public boolean mkdir()
Example: File f = new File (“newdir”);
boolean b = f.mkdir();
OR
new File (“newdir”).mkdir();

The mkdirs() method


 Createsa directory and all the parents of the directory
Syntax: public boolean mkdirs()
Example: File f = new File (“tmp/one/two/three”);
boolean b = f.mkdirs();
OR
new File (“tmp/one/two/three”).mkdirs();

Example for Creating Directories

© Ganapathi Nayak K
11
Streams

Stream
A logical entity that either produces or consumes information
 Linked to a physical device by the Java I/O system
 All streams behave in the same manner, even if the actual physical devices they are
linked to differ

Reading information into a program Writing information out of a program

The java.io package has a number of classes and interfaces to handle I/O

© Ganapathi Nayak K
12
Streams

Closeable and Flushable interfaces


Objects of a class that implements Closeable can be closed
 Defines close () method
void close () throws IOException
 Closes the invoking stream, releasing any resources that it is holding

Objects of a class that implements Flushable can force buffered output to be


written to the stream to which the object is attached
 Defines flush () method
void flush () throws IOException
 Flushing a stream causes buffered output to be physically written to the specified
device

Note: FileNotFoundException is a subclass of IOException

© Ganapathi Nayak K
13
Streams

The Stream Classes


Java I/O : built upon four abstract classes (used to build concrete
subclasses)
 InputStream and OutputStream
– Designed for byte streams
– Used for working with bytes and binary objects
– Abstract methods
» InputStream: read() to read a byte of data
» OutputStream: write() to write a byte of data
 Reader and Writer
– Designed for character streams
– Used for working with characters and strings
– Abstract methods
» Reader: read() to read a character
» Writer: write() to write a character

© Ganapathi Nayak K
14
Streams

The Stream Classes (Continued …)

© Ganapathi Nayak K
15
Streams

InputStream

Abstract class; Implements Closeable interface

Methods throw IOException (except mark() and markSupported())

© Ganapathi Nayak K
16
Streams

InputStream (Continued …)

Method Description

✓ Returns an integer representation of the next available


int read ( ) byte of input.
✓ Returns –1 when end-of-file is encountered.

✓ Attempts to read up to buffer.length bytes into buffer.


int read (byte buffer[ ]) ✓ Returns the actual number of bytes successfully read.
✓ Returns –1 when end-of-file is encountered.
✓ Attempts to read up to numBytes bytes into buffer
read (byte buffer[ ], starting at buffer[offset].
int int offset,
✓ Returns the number of bytes successfully read.
int numBytes)
✓ Returns –1 when end-of-file is encountered.

✓ Returns the number of bytes of input currently available


int available ( )
for reading.

Methods defined by InputStream

© Ganapathi Nayak K
17
Streams

InputStream (Continued …)

Method Description

✓ Closes the input source.


void close ( )
✓ Further read attempts will generate an IOException.
✓ Places a mark at the current point in the input
void mark (int numBytes) stream that remains valid until numBytes bytes are
read.

void reset ( ) ✓ Resets the input pointer to the previously set mark.

✓ Returns true if mark( )/reset( ) are supported by


boolean markSupported ( )
the invoking stream.

✓ Ignores (that is, skips) numBytes bytes of input,


long skip (long numBytes)
returning the number of bytes actually ignored.

Methods defined by InputStream

© Ganapathi Nayak K
18
Streams

OutputStream

Abstract class; Implements Closeable and Flushable interfaces

Methods throw IOException (except mark() and markSupported())

© Ganapathi Nayak K
19
Streams

OutputStream (Continued …)

Method Description

✓ Writes a single byte to an output stream. The parameter


void write (int b) is an int, which allows us to call write( ) with expressions
without having to cast them back to byte.

void write (byte buffer[ ]) ✓ Writes a complete array of bytes to an output stream.

write (byte buffer[ ],


✓ Writes a subrange of numBytes bytes from the array
void int offset,
buffer, beginning at buffer[offset].
int numBytes)

✓ Closes the output stream.


void close ( )
✓ Further write attempts will generate an IOException.

✓ Finalizes the output state so that all buffers are cleared


void flush ( )
(flushes the output buffers).

Methods defined by OutputStream


© Ganapathi Nayak K
20
Byte Streams

FileInputStream
Creates an InputStream to read bytes from a file
Constructors (can throw FileNotFoundException)
 FileInputStream(String filePath) // full path name of the file
Ex: FileInputStream f0 = new FileInputStream (“test.txt”);
 FileInputStream(File fileObj) // file object describes the file
Ex: File f = new File (“test.txt”);
FileInputStream f1 = new FileInputStream(f);

FileInputStream overrides six methods of InputStream (except mark() and


reset())
 Attempt to use mark()/reset() generates java.io.IOException (mark() and reset() not
supported)

Example for FileInputStream

© Ganapathi Nayak K
21
Byte Streams

FileOutputStream
Creates an OutputStream to write bytes to a file
Constructors (can throw IOException in case of read-only files)
 FileOutputStream(String filePath) // full path name of the file
Ex: FileOutputStream f0 = new FileOutputStream (“test.txt”);
 FileOutputStream(File fileObj) // file object describes the file
Ex: File f = new File (“test.txt”);
FileOutputStream f1 = new FileOutputStream(f);
 FileOutputStream(String filePath, boolean append)
Ex: FileOutputStream f2 = new FileOutputStream (“test.txt”, true);
 FileOutputStream(File fileObj, boolean append)
Ex: File f = new File (“test.txt”);
FileOutputStream f3 = new FileOutputStream(f, false);

Example for FileOutputStream

© Ganapathi Nayak K
22
Byte Streams

ByteArrayInputStream
Implements an input stream that uses a byte array as the source
Fields (protected)

Field Description

byte[] buf Array of bytes to hold the inputs

int count Index one greater than the last valid character in the input stream buffer

int mark Currently marked position in the stream

int pos Index of the next character to be read from the stream buffer

© Ganapathi Nayak K
23
Byte Streams

ByteArrayInputStream (Continued …)
Constructors
 ByteArrayInputStream (byte array[])
– Creates a stream from the specified byte array that uses buf as its internal buffer
 ByteArrayInputStream (byte array[], int start, int numBytes)
– Creates a stream from the specified part of the byte array that uses buf as its
internal buffer

Example:
String temp = “Manipal”;
byte b[] = temp.getBytes();
ByteArrayInputStream b1 = new ByteArrayInputStream(b);
ByteArrayInputStream b2 = new ByteArrayInputStream(b, 1, 3);

Example for ByteArrayInputStream

© Ganapathi Nayak K
24
Byte Streams

ByteArrayOutputStream
Implements an output stream that uses a byte array as the destination
Fields (protected)

Field Description

byte[] buf Buffer where data is stored

int count Number of valid bytes in the buffer

© Ganapathi Nayak K
25
Byte Streams

ByteArrayOutputStream (Continued …)
Constructors
 ByteArrayOutputStream()
– A buffer of 32 bytes is created
 ByteArrayOutputStream(int numBytes)
– A buffer of size numBytes is created
– Number of bytes held by the buffer is contained in the protected count field of
ByteArrayOutputStream

Example for ByteArrayOutputStream

© Ganapathi Nayak K
26
Byte Streams

Buffered Byte Streams


A memory buffer is attached to the I/O stream
 Allows Java to do I/O operations on more than one byte a time
– increases performance
 Skipping, marking and resetting of the stream becomes possible

3 buffered byte stream classes


 BufferedInputStream

 BufferedOutputStream

 PushbackInputStream

© Ganapathi Nayak K
27
Byte Streams

BufferedInputStream
Wrap any InputStream into buffered stream
Fields (protected)

Field Description

byte[] buf Internal buffer where the data is stored

int count Index one greater than the last valid byte in buf

Maximum read ahead allowed after a call to the mark method before
int marklimit
subsequent calls to the reset method

int markpos Value of the pos field at the time the last mark method was called

int pos Current position in buf

InputStream in Input stream to be filtered

© Ganapathi Nayak K
28
Byte Streams

BufferedInputStream (Continued …)
Constructors
 BufferedInputStream (InputStream in)
– Creates a buffered input stream
– Default buffer size (8192 characters)

 BufferedInputStream (InputStream in, int bufSize)


– Creates a buffered input stream with the specified buffer size
– Sizes multiples of a memory page, a disk block – improves performance

Supports mark() and reset() in addition to read() and skip()


 BufferedInputStream.markSupported() always returns true

© Ganapathi Nayak K
29
Byte Streams

BufferedOutputStream
Similar to any OutputStream except that flush() method is added
To physically write data buffers

Fields (protected)

Field Description

byte[] buf Internal buffer where the data is stored

int count Number of valid bytes in buf

OutputStream in Output stream to be filtered

© Ganapathi Nayak K
30
Byte Streams

BufferedOutputStream (Continued …)
Constructors
 BufferedOutputStream (OutputStream out)
– Creates a new buffered output stream to write data to the specified output stream
– Default buffer size (8192 characters)

 BufferedOutputStream (OutputStream out, int bufSize)


– Creates a new buffered output stream to write data to the specified output stream
with specified buffer size
– Sizes multiples of a memory page, a disk block – improves performance

© Ganapathi Nayak K
31
Byte Streams

PrintStream
Provides all output capabilities of System.out
 Implements Appendable, Closeable and Flushable interfaces

Fields
 protected OutputStream out

Constructors
 PrintStream (OutputStream out)
 PrintStream (OutputStream out, boolean flushOnNewline)
 PrintStream (OutputStream out, boolean flushOnNewline, String charSet)
throws UnsupportedEncodingException

© Ganapathi Nayak K
32
Byte Streams

PrintStream (Continued …)
Write output to a file
 Can be created from a File object or by specifying a file name
 Existing file will be deleted

Constructors
 PrintStream (File outputFile) throws FileNotFoundException
 PrintStream (File outputFile, String charSet)
throws FileNotFoundException, UnsupportedEncodingException
 PrintStream (String outputFileName) throws FileNotFoundException
 PrintStream (String outputFileName, String charSet)
throws FileNotFoundException, UnsupportedEncodingException

© Ganapathi Nayak K
33
Byte Streams

PrintStream (Continued …)
Supports print() and println() methods
 Ifan argument is not a primitive type, it calls the object’s toString() method and then
display the result

The printf() method (added with the release of JDK 5) supports formatted
output
 Constructors

– PrintStream printf (String fmtString, Object … args)

Example for PrintStream

© Ganapathi Nayak K
34
Byte Streams

DataOutputStream
Write primitive data to a stream
Constructor
 DataOutputStream (OutputStream out)
– Creates a data output stream that uses the specified output stream
 Defines methods to convert values of a primitive type into a byte sequence and then
write it to the output stream
– final void writeDouble (double value) throws IOException
– final void writeBoolean (boolean value) throws IOException
– final void writeInt (int value) throws IOException

Example for DataOutputStream

© Ganapathi Nayak K
35
Byte Streams

DataInputStream
Read primitive data from a stream
Constructor
 DataInputStream (InputStream is)
– Creates a data input stream that uses the specified input stream
 Defines methods to read a sequence of bytes from the stream and then convert them
into values of a primitive type
– double readDouble () throws IOException
– boolean readBoolean () throws IOException
– int readInt () throws IOException

Example for DataInputStream

© Ganapathi Nayak K
36
Byte Streams

RandomAccessFile
Encapsulates a random-access file
 Not derived from InputStream or OutputStream classes
 Implements DataInput and DataOutput interfaces
 Supports positioning of file pointer within the file

© Ganapathi Nayak K
37
Byte Streams

RandomAccessFile
Constructors
 RandomAccessFile (File fileObj, String access) throws IOException
 RandomAccessFile (String fileName, String access) throws IOException

Access modes:
 ‘r’ – read only
 ‘rw’ – read-write
 ‘rws’ - opened for read-write, updates file’s data and metadata
 ‘rwd’ - opened for read-write, updates only file’s data
(metadata is updated on file closure)

© Ganapathi Nayak K
38
Byte Streams

RandomAccessFile (Continued …)

Method Description

Closes the random access file stream and releases any


void close ()
system resources associated with the stream

long getFilePointer () Returns the current offset in the file

long length () Returns the length of the file

Sets the file-pointer offset, measured from the beginning


void seek (long pos)
of the file, at which next read or write occurs

void setLength (long newLen) Sets the length of the file

Attempts to skip over n bytes of input discarding the


int skipBytes (int n)
skipped bytes

© Ganapathi Nayak K
39
Byte Streams

RandomAccessFile (Continued …)

Method Description

int read () Reads a byte of data

Reads up to b.length bytes of data into the array of


int read (byte[] b)
bytes

Reads up to len bytes of data from position offset


int read (byte[], int off, int len)
into the array of bytes

void write (int b) Writes the specified byte

Writes b.length bytes of data from the specified byte


void write (byte[] b)
array

Writes len bytes of data from position offset from


void write (byte[], int off, int len)
the specified byte array

© Ganapathi Nayak K
40
Byte Streams

RandomAccessFile (Continued …)

Method Method

boolean readBoolean () void writeBoolean (boolean b)

byte readByte () void writeByte (byte b)

char readChar () void writeChar (char c)

double readDouble () void writeDouble (double d)

float readFloat () void writeFloat (float f)

String readLine () void writeBytes (String str)

int readInt () void writeInt (int i)

long readLong () void writeLong (long l)

short readShort () void writeShort (short s)

Example for RandomAccessFile

© Ganapathi Nayak K
41
Character Streams

Reader

© Ganapathi Nayak K
42
Character Streams

Reader (Continued …)
Reader – an abstract class – defines streaming character input

Method Description

✓ Returns an integer representation of the next available


int read ( ) character from the invoking input stream.
✓ Returns –1 when end-of-file is encountered.

✓ Attempts to read up to buffer.length characters into buffer


int read (char buffer[ ]) and returns the actual number of bytes successfully read.
✓ Returns –1 when end-of-file is encountered.

✓ Attempts to read up to numChars characters into buffer


read (char buffer[ ], starting at buffer[offset], returning the number of characters
int int offset, successfully read.
int numChars)
✓ Returns –1 when end-of-file is encountered.

Methods defined by Reader

© Ganapathi Nayak K
43
Character Streams

Reader (Continued …)

Method Description

✓ Closes the input source.


void close ( )
✓ Further read attempts will generate an IOException.

mark ✓ Places a mark at the current point in the input stream


void
(int numChars) that remains valid until numChars characters are read.

void reset ( ) ✓ Resets the input pointer to the previously set mark.

✓ Returns true if mark( )/reset( ) are supported by the


boolean markSupported ( )
invoking stream.

skip ✓ Ignores (that is, skips) numChars characters of input,


long
(long numChars) returning the number of characters actually ignored.

Methods defined by Reader

© Ganapathi Nayak K
44
Character Streams

Writer

© Ganapathi Nayak K
45
Character Streams

Writer (Continued …)
Writer – an abstract class – defines streaming character output

Method Description

✓ Appends ch to the end of the invoking output stream.


Writer append (char ch)
✓ Returns a reference to the invoking stream.

✓ Appends chars to the end of the invoking output


append stream.
Writer
(CharSequence chars)
✓ Returns a reference to the invoking stream.

append ✓ Appends the subrange of chars specified by begin and


Writer (CharSequence chars, end–1 to the end of the invoking output stream.
int begin, int end) ✓ Returns a reference to the invoking stream.

Methods defined by Writer

© Ganapathi Nayak K
46
Character Streams

Writer (Continued …)

Method Description

void write (char ch) ✓ Writes a single character to the invoking output stream.

write ✓ Writes a complete array of characters to the invoking


void
(char buffer[ ]) output stream.

write
✓ Writes a sub-range of numChars characters from the
abstract (char buffer[ ],
array buffer, beginning at buffer[offset] to the invoking
void int offset,
output stream.
int numChars)

Methods defined by Writer

© Ganapathi Nayak K
47
Character Streams

Writer (Continued …)

Method Description

void write (String str) ✓ Writes str to the invoking output stream.

write (String str, int ✓ Writes a sub-range of numChars characters from


void
offset, int numChars) the string str, beginning at the specified offset.

abstract ✓ Closes the output stream. Further write attempts


close ( )
void will generate an IOException.

abstract ✓ Finalizes the output state so that any buffers are


flush ( )
void cleared. That is, it flushes the output buffers.

Methods defined by Writer

© Ganapathi Nayak K
48
Character Streams

FileReader
Creates a Reader that can be used to read from a file
Fields (protected)
Object lock – Object used to synchronize operations on this stream

Constructors (can throw FileNotFoundException)


 FileReader (String filePath)
 FileReader (File fileObj)

Example for FileReader

© Ganapathi Nayak K
49
Character Streams

FileWriter
Creates a Writer that can be used to write to a file
Fields (protected)
Object lock – Object used to synchronize operations on this stream

Constructors (can throw IOException)


 FileWriter (String filePath)
 FileWriter (String filePath, boolean append)
 FileWriter (File fileObj)
 FileWriter (File fileObj, boolean append)

Example for FileWriter

© Ganapathi Nayak K
50
Character Streams

CharArrayReader
Implementation of the input stream that uses character array as the source
Fields (protected)

Field Description

char[] buf Internal character buffer where the data is stored

int count Index of the end of buf

int markedPos Position of the mark in buf

int pos Current position in buf

Object lock Used to synchronize operations on this stream

© Ganapathi Nayak K
51
Character Streams

CharArrayReader (Continued …)
Constructors (can throw IOException)
 CharArrayReader (char array[])
– Creates a character array reader from the specified array of characters
 CharArrayReader (char array[], int start, int numChars)
– Creates a character array reader from the specified part of the array of characters

Example for CharArrayReader

© Ganapathi Nayak K
52
Character Streams

CharArrayWriter
Implementation of the output stream that uses character array as the
destination
Fields (protected)

Field Description

char[] buf Internal character buffer where the data is stored

int count Number of characters in buf

Object lock Used to synchronize operations on this stream

© Ganapathi Nayak K
53
Character Streams

CharArrayWriter (Continued …)
Constructors (can throw IOException)
 CharArrayWriter ()
– Creates a character array reader with a default size (8192 bytes)
 CharArrayWriter (int numChars)
– Creates a character array reader with the specified size

Example for CharArrayWriter

© Ganapathi Nayak K
54
Character Streams

BufferedReader
Improves performance by buffering input
Constructors (can throw IOException)
 BufferedReader (Reader inputStream)
– Creates a buffered stream using default buffer size (8192 characters)
 BufferedReader (Reader inputStream, int bufSize)
– Size of the buffer is passed in bufSize

© Ganapathi Nayak K
55
Character Streams

BufferedWriter
Improves performance by buffering output
Constructors (can throw IOException)
 BufferedWriter (Writer outputStream)
– Creates a buffered stream using default buffer size (8192 characters)
 BufferedWriter (Writer outputStream, int bufSize)
– Size of the buffer is passed in bufSize

© Ganapathi Nayak K
56
Predefined Streams

System class (java.lang)


Contains three predefined stream variables: in, out and err
 Declared as public, static and final within System class (can be called without System
object)
 in is an object of type InputStream
 out and err are objects of type PrintStream

© Ganapathi Nayak K
57
Predefined Streams

Reading Console Input


Accomplished by reading from System.in (byte stream)
 To
obtain a character based stream attached to the console, wrap System.in in a
BufferedReader object (supports buffered input stream)

Example
InputStreamReader in = new InputStreamReader (System.in);
BufferedReader br = newBufferedReader (in);
OR
BufferedReader br = newBufferedReader (new InputStreamReader(System.in));
br is the character-based stream that is linked to the console through System.in

© Ganapathi Nayak K
58
Predefined Streams

Reading Console Input (Continued ….)


Reading characters
 Usage
int read() throws IOException
 Example
char c = (char) br.read();

Reading strings
 Usage
String readLine() throws IOException
 Example
String s = br.readLine();

© Ganapathi Nayak K
59
Predefined Streams

Writing Console Output


Simple methods: print(), println() and printf()
Using write() method of PrintStream (derived from output stream)
 Usage
void write (int byteVal)
 Example
int b;
b = ‘A’;
System.out.write (b);
System.out.write(‘\n’);

© Ganapathi Nayak K
60
Serialization

Object Serialization and Deserialization

Mechanism where characteristics (state) of an object is written to a bytes


stream
 Object’s data

 Information about the objects type and types of data stored in the object

Write serialized object to a persistent storage (disk file)

Object can be restored using deserialization

JVM independent

 Object can be serialized in one platform and deserialized in another platform


© Ganapathi Nayak K
62
Serialization

Serializable Interface

A built-in interface in java.io package

 Defines no members

 Indicates that a class may be serialized

– If a class is serializable, all its subclasses are also serializable

An object of a class that implements this interface can be serialized

Variables declared as transient or static cannot be saved by serialization

© Ganapathi Nayak K
63
Serialization

ObjectOutput Interface
Extends DataOutput interface and supports object serialization

Method Description

void write (byte buffer[ ]) ✓ Writes an array of bytes to the invoking stream.

write (byte buffer[ ], ✓ Writes a subrange of numBytes bytes from the array
void
int offset, int numBytes) buffer, beginning at buffer[offset].

✓ Writes a single byte to the invoking stream.


void write (int b)
✓ The byte written is the low-order byte of b.

void writeObject (Object obj) ✓ Writes object obj to the invoking stream.

✓ Closes the invoking stream.


void close ( )
✓ Further write attempts will generate an IOException.
✓ Finalizes the output state so that all buffers are
void flush ( )
cleared (flushes the output buffers).

Methods defined by ObjectOutput interface


© Ganapathi Nayak K
64
Serialization

ObjectOutputStream Class
Extends OutputStream class and implements ObjectOutput interface
 Responsible for writing objects to a stream

Constructor
ObjectOutputStream (OutputStream out) throws IOException
 Argument out is the output stream to which serialized object will be written

All methods throw IOException

© Ganapathi Nayak K
65
Serialization

ObjectOutputStream Class (Continued …)

Method Description

void write (byte buffer[ ]) ✓ Writes an array of bytes to the invoking stream.

write (byte buffer[ ], ✓ Writes a subrange of numBytes bytes from the


void
int offset, int numBytes) array buffer, beginning at buffer[offset].

✓ Writes a single byte to the invoking stream.


void write (int b)
✓ The byte written is the low-order byte of b.

void writeBoolean (boolean b) ✓ Writes a boolean to the invoking stream.

✓ Writes a byte to the invoking stream.


void writeByte (int b)
✓ The byte written is the low-order byte of b.

Methods defined by ObjectOutputStream Class

© Ganapathi Nayak K
66
Serialization

ObjectOutputStream Class (Continued …)

Method Description

✓ Writes the bytes representing str to the invoking


void writeBytes (String str)
stream.

void writeChar (int c) ✓ Writes a char to the invoking stream.

void writeChars (String str) ✓ Writes the characters in str to the invoking stream.

void writeDouble (double d) ✓ Writes a double to the invoking stream.

void writeFloat (float f ) ✓ Writes a float to the invoking stream.

void writeInt (int i) ✓ Writes an int to the invoking stream.

Methods defined by ObjectOutputStream Class

© Ganapathi Nayak K
67
Serialization

ObjectOutputStream Class (Continued …)

Method Description

void writeLong (long l) ✓ Writes a long to the invoking stream.

void writeShort (int i) ✓ Writes a short to the invoking stream.

final void writeObject (Object obj) ✓ Writes obj to the invoking stream.

✓ Closes the invoking stream.


void close ( ) ✓ Further write attempts will generate an
IOException.

✓ Finalizes the output state so that all buffers are


void flush ( )
cleared (flushes the output buffers).

Methods defined by ObjectOutputStream

© Ganapathi Nayak K
68
Serialization

ObjectInput Interface
Extends DataInput interface and supports object serialization

Method Description

✓ Returns an integer representation of the next available


void read () byte of input.
✓ Returns –1 when end-of-file is encountered.

✓ Attempts to read up to buffer.length bytes into buffer,


void read (byte buffer[ ]) returning the number of bytes successfully read.
✓ Returns –1 when end-of-file is encountered.

✓ Attempts to read up to numBytes bytes into buffer


read (byte buffer[ ], starting at buffer[offset], returning the number of
void bytes successfully read.
int offset, int numBytes)
✓ Returns –1 when end-of-file is encountered.

Methods defined by ObjectInput interface


© Ganapathi Nayak K
69
Serialization

ObjectInput Interface (Continued …)


Extends DataInput interface and supports object serialization

Method Description

Object readObject ( ) ✓ Reads an object from the invoking stream.

✓ Skips numBytes bytes in the invoking stream.


long skip (long numBytes)
✓ Returns the number of bytes actually skipped.

✓ Returns the number of bytes that are now available in


int available ( )
the input buffer.

✓ Closes the invoking stream.


void close ( )
✓ Further read attempts will generate an IOException.

Methods defined by ObjectInput interface

© Ganapathi Nayak K
70
Serialization

ObjectInputStream Class

Extends InputStream class and implements ObjectInput interface


 Responsible for reading objects from a stream

Constructor
ObjectInputStream (InputStream in) throws IOException

 Argument in is the input stream from which serialized object will be read

All methods throw IOException

© Ganapathi Nayak K
71
Serialization

ObjectInputStream Class (Continued …)

Method Description

✓ Returns an integer representation of the next


int read ( ) available byte of input.
✓ Returns –1 when end-of-file is encountered.

✓ Attempts to read up to numBytes bytes into


read (byte buffer[ ], buffer starting at buffer[offset], returning the
int number of bytes successfully read.
int offset, int numBytes
✓ Returns –1 when end-of-file is encountered.

✓ Reads and returns a boolean from the invoking


boolean readBoolean ( )
stream.

✓ Reads and returns a byte from the invoking


byte readByte ( )
stream.

Methods defined by ObjectInputStream Class

© Ganapathi Nayak K
72
Serialization

ObjectInputStream Class (Continued …)

Method Description

char readChar ( ) Reads and returns a char from the invoking stream.

double readDouble ( ) Reads and returns a double from the invoking stream.

float readFloat ( ) Reads and returns a float from the invoking stream.

int readInt ( ) Reads and returns an int from the invoking stream.

long readLong ( ) Reads and returns a long from the invoking stream.

short readShort ( ) Reads and returns a short from the invoking stream.

Methods defined by ObjectInputStream Class

© Ganapathi Nayak K
73
Serialization

ObjectInputStream Class (Continued …)

Method Description

final Object readObject ( ) Reads and returns an object from the invoking stream.

Returns the number of bytes that are now available in


int available ( )
the input buffer.

Closes the invoking stream. Further read attempts will


void close ( )
generate an IOException.

Methods defined by ObjectInputStream Class

© Ganapathi Nayak K
74
Serialization

Implementation
Create a class to implement Serializable interface
Serialization
 Create a FileOutputStream to refer to a file named “Student.ser”
 Create an ObjectOutputStream for this file stream
 Use writeObject() method of ObjectOutputStream to serialize the object
 Flush and close the ObjectOutputStream

Deserialization
 Create a FileInputStream to refer to the file named “Student.ser”
 Create an ObjectInputStream for this file stream
 Use readObject() method of ObjectInputStream to deserialize the object
 Close the ObjectInputStream

Example for Serialization and Deserialization

© Ganapathi Nayak K
75
The End

© Ganapathi Nayak K
76

You might also like