0% found this document useful (0 votes)
2 views86 pages

Unit4 Streams FileHandling

The document covers the concept of streams and file handling in Java, focusing on Java I/O operations, including serialization and deserialization. It explains the classification of streams into character and byte streams, along with their respective classes and methods for reading and writing files. Additionally, it discusses the use of standard streams, file input/output streams, and the BufferedReader and BufferedWriter classes for efficient data handling.

Uploaded by

rathisg1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views86 pages

Unit4 Streams FileHandling

The document covers the concept of streams and file handling in Java, focusing on Java I/O operations, including serialization and deserialization. It explains the classification of streams into character and byte streams, along with their respective classes and methods for reading and writing files. Additionally, it discusses the use of standard streams, file input/output streams, and the BufferedReader and BufferedWriter classes for efficient data handling.

Uploaded by

rathisg1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link].

SEM II
Course Code: CDT2001

Unit 4 : Streams-File Handling


Serialization-Deserialization

By,
Prof. Vaishali Katkar,
Department of CSE ( Data Science )
RCOEM, Nagpur.
Concept of Streams

Prof. Vaishali Katkar


Java I/O

• Java I/O (Input and Output) is used to process the


input and produce the output
• Java uses the concept of a stream to make I/O operation fast.
• The [Link] package contains all the classes required for input and
output operations
• We can perform file handling in Java by Java I/O API

Prof. Vaishali Katkar


Java I/O

Prof. Vaishali Katkar


Streams

• Stream is an abstraction that either produces or consumes information

• Stream is a flow /sequence of data

• It is the channel through which data is input or output in a java program

• An input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket

• Likewise, an output stream may refer to the console, a disk file, or a network
connection

Prof. Vaishali Katkar


Why is Stream an Abstraction?

• All streams behave in the same manner, even if the actual physical devices to which they are linked
differ

• Thus, the same I/O classes and methods can be applied to different types of devices

• This means that an input/output stream can abstract many different kinds of input/output

Prof. Vaishali Katkar


Overview of I/O Streams

• To bring/read in information, a program opens a stream on an information source (a file,


memory, a socket) and reads the information sequentially, as shown in the following figure.

Prof. Vaishali Katkar


Overview of I/O Streams

• Similarly, a program can send/write information to an external destination by


opening a stream to a destination and writing the information out sequentially, as
shown in the following figure.

Prof. Vaishali Katkar


Overview of I/O streams

Prof. Vaishali Katkar


Overview of I/O streams

• The [Link] package contains a collection of stream classes that support


algorithms for reading and writing

• To use these classes, a program needs to import the [Link] package

• The stream classes are divided into two class hierarchies, based on the data
type (either characters or bytes) on which they operate i.e

• Character Stream
and
• Byte Stream

Prof. Vaishali Katkar


Character Streams

• Reader and Writer are the abstract superclasses for character


streams in [Link]

• Reader provide streams that read 16-bit characters and Writer


provides the streams that write 16-bit characters

• Character streams are more efficient than byte streams

Prof. Vaishali Katkar


Byte Streams

• To read and write 8-bit bytes, programs should use the byte streams,
descendants of InputStream and OutputStream

• InputStream and OutputStream provide streams that read 8-bit bytes and
write 8-bit bytes

• Byte streams are used, for example, when reading or writing binary data
such as images and audio

Prof. Vaishali Katkar


Byte Streams

• Byte streams can deal with transfer of ASCII characters ranging


0 to 255

• JAVA supports Unicode characters that are 16 bits long

• Character streams support Unicode characters

Prof. Vaishali Katkar


Prof. Vaishali Katkar
Prof. Vaishali Katkar
Byte Streams (cont.)
• The class hierarchy for the InputStream Class

Prof. Vaishali Katkar


Byte Stream (cont.)
• Class hierarchy for Output Class

Prof. Vaishali Katkar


Prof. Vaishali Katkar
Character Streams Contd.
•The following figure shows the class hierarchies for the Reader and Writer classes

Prof. Vaishali Katkar


Prof. Vaishali Katkar
Standard Streams
• JAVA provides support for standard I/O i.e. keyboard and console

• System is a class in [Link] package

• in, out and err are public static and final variables in System class

• in- object of InputStream

• out, err – objects of PrintStream

• Three predefined streams are available to a program

• [Link] – to read input from keyboard

• [Link] – to output the data produced by user program to console

• [Link] – to output the error data produced by user program to console

Prof. Vaishali Katkar


Reading and Writing Files
• Byte oriented File I/O
– FileInputStream
– FileOutputStream

• Character oriented File I/O


– FileReader
– FileWriter

Prof. Vaishali Katkar


Using FileInputStream
• FileInputStream(String fileName) throws FileNotFoundException
• FileOutputStream(String fileName) throws FileNotFoundException
•Used to read from file
FileInputStream f = new FileInputStream ("C:/java/[Link]");

File f = new File("C:/java/hello");


FileInputStream f = new FileInputStream(f);

Prof. Vaishali Katkar


FileInputStream methods

• public void close( ) throws IOException{ }


This method closes the file input stream. Releases any system resources associated
with the file. Throws an IOException

• public int read( ) throws IOException{ }


Reads the integer representation of next available byte. On end of file returns -1

• public int read(byte[] r) throws IOException{ }


This method reads r length bytes from the input stream into an array. Returns the
total number of bytes read. If end of file -1 will be returned

Prof. Vaishali Katkar


Closing a File
• When you are done with a file, you must close it
• Done by calling the close( ) method, which is implemented by both FileInputStream and
FileOutputStream
void close( ) throws IOException
• Closing a file releases the system resources allocated to the file, allowing them to be used
by another file
• Failure to close a file can result in “memory leaks” because of unused resources remaining
allocated
• There are two ways to close a file
• close( ) method
• Try with resources

Prof. Vaishali Katkar


Sample Program

• WAP to display the contents of a file that contains ASCII text

Prof. Vaishali Katkar


Using FileOutputStream
•Used to create a file and write into it
FileOutputStream f = new FileOutputStream("C:/java/hello")

File f = new File("C:/java/hello");


FileOutputStream f = new FileOutputStream(f);

Prof. Vaishali Katkar


FileOutputStream methods
•public void close() throws IOException{}
•This method closes the file output stream. Releases any system resources associated with the
file. Throws an IOException

•public void write(int w)throws IOException{}


• This methods writes the specified byte to the output stream. Although w is declared as an
integer, only the low-order eight bits are written to the file

•public void write(byte[] w)


•Writes w length bytes from the byte array to the OutputStream

Prof. Vaishali Katkar


Sample Program

• WAP to copy a file called [Link] to a file called [Link]

Prof. Vaishali Katkar


Automatically Closing a File : Automatic Resource Management
(ARM)

• Use try with resource


try (resource-specification)
{
// use the resource
}
Here, resource-specification is a statement that declares and initializes a resource
When the try block ends, the resource is automatically released
• Thus, there is no need to call close( ) explicitly
• The try-with-resources statement can be used only with those resources that implement the
AutoCloseable interface defined by [Link]

Prof. Vaishali Katkar


Example

• The following code uses a try-with-resources statement to open a file and then automatically close
it when the try block is left

try(FileInputStream fin = new FileInputStream(args[0]))


{
do
{
i = [Link]( );
if(i != -1)
[Link]((char) i);
}while(i != -1);
}
catch(IOException e)
{
[Link]("File Not Found.");
}

Prof. Vaishali Katkar


Try with resource
• The resource declared in the try statement is implicitly final

• This means that you can’t assign to the resource after it has been created. Also, the scope of the
resource is limited to the try-with-resources statement

• You can manage more than one resource within a single try statement. To do so, simply separate each
resource specification with a semicolon

• try (FileInputStream fin = new FileInputStream(args[0]);

• FileOutputStream fout = new FileOutputStream(args[1]))

Prof. Vaishali Katkar


Java FileReader Class
• Java FileReader class is used to read data from the file

• It returns data in byte format like FileInputStream class

• It is character-oriented class which is used for file handling in Java

• Java FileReader class declaration

• public class FileReader extends InputStreamReader

Prof. Vaishali Katkar


Constructors of FileReader class

Constructor Description
FileReader(String file) It gets filename in string. It opens the
given file in read mode. If file doesn't
exist, it throws
FileNotFoundException.
FileReader(File file) It gets filename in file instance. It
opens the given file in read mode. If
file doesn't exist, it throws
FileNotFoundException.

Prof. Vaishali Katkar


Methods of FileReader class

Method Description

int read( ) It is used to return a character in


ASCII form. It returns -1 at the end
of file.

void close( ) It is used to close the FileReader


class.

Prof. Vaishali Katkar


Java FileReader Example
• In this example, we are reading the data from the text file [Link] using Java FileReader
class
package filereader;
import [Link];
public class FileReaderExample1
{

public static void main(String args[ ])throws Exception


{
FileReader fr=new FileReader("D:\\[Link]");
int i;
while((i=[Link]( ))!=-1)
[Link]((char)i);
[Link]();
}
}
Prof. Vaishali Katkar
File Writer

• Java FileWriter class is used to write character-oriented data to a file


• It is character-oriented class which is used for file handling in java
• Unlike FileOutputStream class, you don't need to convert string into byte array because it provides
method to write string directly
• Java FileWriter class declaration
• public class FileWriter extends OutputStreamWriter

Prof. Vaishali Katkar


Constructors of FileWriter class

Constructor Description

FileWriter(String file) Creates a new file. It gets file name


in string.

FileWriter(File file) Creates a new file. It gets file name in


File object.

Prof. Vaishali Katkar


Methods of FileWriter class
Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[ ] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Prof. Vaishali Katkar


Java FileWriter Example
• In this example, we are writing the data in the file [Link] using Java FileWriter class.

package filewriter;
import [Link];
public class FileWriterExample1
{
public static void main(String args[ ]){
try{
FileWriter fw=new FileWriter("D:\\[Link]");
[Link]("Hello World");
[Link]( );
}catch(Exception e)
{[Link](e);}
[Link]("Success...");
}
}
Prof. Vaishali Katkar
Java BufferedWriter Class

• Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast
• It inherits Writer class
• The buffering characters are used for providing the efficient writing of single arrays,
characters, and strings
• Class declaration
• public class BufferedWriter extends Writer

Prof. Vaishali Katkar


Class constructors

Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character
output stream that uses the default
size for an output buffer.

BufferedWriter(Writer wrt, int size) It is used to create a buffered character


output stream that uses the specified
size for an output buffer.

Prof. Vaishali Katkar


Class methods
Method Description
void newLine() It is used to add a new line by writing
a line separator.
void write(int c) It is used to write a single character.

void write(char[ ] cbuf, int off, int len) It is used to write a portion of an array
of characters.
void write(String s, int off, int len) It is used to write a portion of a string.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Prof. Vaishali Katkar


Example of Java BufferedWriter
• Let's see the simple example of writing the data to a text file [Link] using Java
BufferedWriter
package bufferedwriter;
import [Link].*;
public class BufferedWriterEample
{
public static void main(String[ ] args) throws Exception
{
FileWriter writer = new FileWriter("D:\\[Link]");
BufferedWriter buffer = new BufferedWriter(writer);
[Link]("Hello World");
[Link]( );
[Link]("Success");
}
}
Prof. Vaishali Katkar
Java BufferedReader Class

• Java BufferedReader class is used to read the text from a character-based input stream
• It can be used to read data line by line by readLine( ) method
• It makes the performance fast
• It inherits Reader class
• Java BufferedReader class declaration
• public class BufferedReader extends Reader

Prof. Vaishali Katkar


Java BufferedReader class constructors
Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character


input stream that uses the default size
for an input buffer.

BufferedReader(Reader rd, int size) It is used to create a buffered character


input stream that uses the specified
size for an input buffer.

Prof. Vaishali Katkar


Java BufferedReader class methods
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of an array.

boolean markSupported() It is used to test the input stream support for the mark and
reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.


void reset() It repositions the stream at a position the mark method was
last called on this input stream.
void mark(int readAheadLimit) It is used for marking the present position in a stream.

void close() It closes the input stream and releases any of the system
resources associated with the stream.

Prof. Vaishali Katkar


Java BufferedReader Example
import [Link].*; • In this example, we are reading the
public class BufferedReaderExample data from the text
{ file [Link] using Java
public static void main(String args[ ])throws Exception BufferedReader class
{
FileReader fr=new FileReader("D:\\[Link]");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]( );
[Link]( );
}
}

Prof. Vaishali Katkar


Reading input from Console
There are 3 ways :
1) InputStreamReader wrapped in a BufferedReader
2) Scanner class
3) Console class

Prof. Vaishali Katkar


Method 1

1) Create an InputStreamReader with [Link]

2) Create BufferedReader using InputStreamReader

3) Get user input by calling BufferedReader methods like, readLine() and read()

Prof. Vaishali Katkar


InputStreamReader

• InputStreamReader is a bridge between byte stream and character stream

• It reads bytes and decodes into character

• Constructor takes an object of InputStream

Prof. Vaishali Katkar


Scanner

• -Class defined in util package


• -Usage
● Scanner scanIn = new Scanner ([Link]);
• -Methods like
● nextLine() - reads line as a string
● nextInt() - reads integer

Prof. Vaishali Katkar


Using Console class

Import [Link];
Console console = [Link]( );
String input = [Link]( );

Prof. Vaishali Katkar


How to Use Pipe Streams

•Pipes are used to channel the output from one thread into the input of another.
PipedReader and PipedWriter (and their input and output stream counterparts
PipedInputStream and PipedOutputStream ) implement the input and output components of a
pipe

Prof. Vaishali Katkar


How to wrap a stream
• Streams are wrapped to combine the various features of the many streams.
• Example code:
• BufferedReader in = new BufferedReader(source);

• The code opens a BufferedReader on source, which is another reader of a different type. This
essentially "wraps" source in a BufferedReader. The program reads from the BufferedReader,
which in turn reads from source.

Prof. Vaishali Katkar


Working with Filter Streams

• The [Link] package provides a set of abstract classes that define and partially
implement filter streams. A filter stream filters data as it's being read from or
written to the stream.
• The filter streams are FilterInputStream , and FilterOutputStream .
• A filter stream is constructed on another stream (the underlying stream).

Prof. Vaishali Katkar


Working with Random Access Files

• A random access file permits non-sequential or random access to a file's contents.


• Using Random Access Files
• Unlike the input and output stream classes in [Link], RandomAccessFile is used for
both reading and writing files. You create a RandomAccessFile object with different
arguments depending on whether you intend to read or write.

Prof. Vaishali Katkar


Write to a File : Example
import [Link];
public class FileIO
{
public static void main(String args[ ])
{
try
{
//BufferedWriter writer=new BufferedWriter( );
BufferedWriter writer=new BufferedWriter(new FileWriter("[Link]") );
[Link]("Writing to a file.");
[Link]("\n Here is another line. ");

[Link]( );
}
catch(IOException e)
{
[Link]( );
}
}
} helps to trace the exception
Prof. Vaishali Katkar
Example:
import [Link];
public class FileIO
{
public static void main(String args[ ])
{
String[ ] names={"John", "Carl", "Jerry"};
try
{
BufferedWriter writer=new BufferedWriter(new FileWriter("[Link]"));
[Link]("Writing to a file.");
[Link]("\n Here is another line.")

for(String name: names)


{
[Link]("\n"+name);
}
[Link]( );

}
catch(IOException e)
{
[Link]();
}
} Vaishali Katkar
Prof.
Read from a File
import [Link]; catch(IOException e)
import [Link]; {
import [Link]; [Link]();
import [Link]; }
import [Link]; try
public class FileIO {
{ BufferedReader reader =new BufferedReader(new FileReader("[Link]"));
public static void main(String args[ ]) [Link]([Link]( ));
{ [Link]( );
String[ ] names={"John", "Carl", "Jerry"};
try }
{ catch(IOException e)
BufferedWriter writer=new BufferedWriter(new FileWriter("[Link]")); {
[Link]("Writing to a file."); [Link]( );
[Link]("\nHere is another line."); }
for(String name: names)
}
{
}
[Link]("\n"+name);
}
[Link]( ); }
Prof. Vaishali Katkar
Read from a File
import [Link]; catch(IOException e)
import [Link]; {
import [Link]; [Link]();
import [Link]; }
import [Link]; try
public class FileIO {
{ BufferedReader reader =new BufferedReader(new FileReader("[Link]"));
public static void main(String args[ ]) String line;
{ while((line=[Link]( ))!=null)
String[ ] names={"John", "Carl", "Jerry"}; {
try [Link](line);
{ } [Link]( );
BufferedWriter writer=new BufferedWriter(new FileWriter("[Link]"));
[Link]("Writing to a file.");
[Link]("\nHere is another line."); }
catch(IOException e)
for(String name: names)
{
{
[Link]( );
[Link]("\n"+name);
}
}
}
[Link]( ); }
}
Prof. Vaishali Katkar
Read from a File
OUTPUT:

Prof. Vaishali Katkar


Example
Write a program to copy the contents of a file [Link] into a file [Link]. Use appropriate classes and methods in
[Link] so that the contents are copied line-by-line.

import [Link].*;
import [Link].*;

public class FileCopy


{
public static void copyContent(File a, File b) throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);

try {
int n;
while ((n = [Link]( )) != -1) // read( ) function to read the byte of data
{
[Link](n); // write( ) function to write the byte of data
}
}

Prof. Vaishali Katkar


Example
finally
{ if (in != null)
{
[Link]( ); }
if (out != null)
{
[Link]( ); }
}
[Link]("File Copied");
}
public static void main(String[ ] args) throws Exception
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the source filename from where you have to read/copy :"); // get the source file name
String a = [Link]( );
File x = new File(a);
[Link]("Enter the destination filename where you have to write/paste :"); // get the source file name
String b = [Link]( );
File y = new File(b);
copyContent(x, y);
}
} Vaishali Katkar
Prof.
Example

Prof. Vaishali Katkar


Serialization and Deserialization

What is Serialization in Java?


• Serialization in Java is the concept of representing an object’s state as a byte
stream.

• The byte stream has all the information about the object.

• Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport
the code from one JVM to another and then de-serialize it there.

• Deserialization is the exact opposite process of serialization where the byte data
type stream is converted back to an object in the memory.

• The best part about these mechanisms is that both are JVM-independent, meaning
you serialize on one JVM and de-serialize on another.

Prof. Vaishali Katkar


Serialization and Deserialization

• Serialization in Java is a mechanism of writing the state of an object into a byte-stream


• The reverse operation of serialization is called deserialization where byte-stream is converted into an
object
• The serialization and deserialization process is platform-independent, it means you can serialize an
object on one platform and deserialize it on a different platform
• For serializing the object, we call the writeObject( ) method of ObjectOutputStream class, and for
deserialization we call the readObject( ) method of ObjectInputStream class
• We must have to implement the Serializable interface for serializing the object

Prof. Vaishali Katkar


Advantages of Serialization
Serialization offers a plethora of benefits. Some of its primary
advantages are:

• Used for marshaling (traveling the state of an object on the network)


• To persist or save an object’s state
• JVM independent
• Easy to understand and customize

Prof. Vaishali Katkar


Points to Note About Serialization in Java
To serialize an object, there are a few conditions to be met. Some other key points need to be
highlighted before you proceed further in the article. These are the conditions and points to remember
while using serialization in Java.

• Serialization is a marker interface with no method or data member


• You can serialize an object only by implementing the serializable interface
• All the fields of a class must be serializable; otherwise, use the transient keyword
• The child class doesn’t have to implement the Serializable interface, if the parent class does
• The serialization process only saves non-static data members, but not static or transient data
members
• By default, the String and all wrapper classes implement the Serializable interface

Prof. Vaishali Katkar


How to Serialize an Object?

You must use the writeObject(c) method of the ObjectOutputStream class for serialization and
readObject(c) method of the InputObjectStream class for deserialization purpose.

Syntax for the writeObject(c) method:

public final void writeObject(Object o) throws IO Exception

Syntax for the readObject( ) method:

public final Object readObject( ) throws IOException, ClassNotFoundException

Prof. Vaishali Katkar


Serialization and Deserialization

Prof. Vaishali Katkar


[Link] interface

• Serializable is a marker interface (has no data member and method). It is used to "mark"
Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

• The Serializable interface must be implemented by the class whose object needs to be
persisted.

• The String class and all the wrapper classes implement the [Link] interface by
default.

Prof. Vaishali Katkar


ObjectOutputStream class
• The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream
• Only objects that support the [Link] interface can be written to streams

Prof. Vaishali Katkar


Constructor
public ObjectOutputStream(OutputStream out) throws IOException {} It creates an ObjectOutputStream that writes
to the specified OutputStream.

Important Methods
Method Description

1) public final void writeObject(Object obj) throws IOException It writes the specified object to the ObjectOutputStream.
{}
2) public void flush() throws IOException {} It flushes the current output stream.
3) public void close() throws IOException {} It closes the current output stream.

Prof. Vaishali Katkar


ObjectInputStream class
• An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.

Constructor
1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that reads from the specified
IOException {} InputStream.

Important Methods
Method Description

1) public final Object readObject() throws IOException, It reads an object from the input stream.
ClassNotFoundException{}
2) public void close() throws IOException {} It closes ObjectInputStream.

Prof. Vaishali Katkar


Serialization example:
import [Link]; public String getName( )
import [Link]; {
import [Link].*; return name;
}
class Student implements Serializable public void setName(String name)
{ {
private String name; [Link]=name;
private int age; }
public int getAge( )
public Student( String name, int age) {
{ return age;
[Link]=name; }
[Link]=age; public void setAge(int age)
} {
public Student( ) [Link]=age;
{ }
} }

Prof. Vaishali Katkar


Serialization example:
public class Serial
{
public static void main(String args[ ])
{
try
{
Student s1=new Student("Ankit", 20);
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
[Link](s1);
[Link]( );
[Link]( );

[Link]("Object state is transfered to file [Link]");


}
catch(IOException e)
{
[Link]( );
} } }
Prof. Vaishali Katkar
Serialization example:
OUTPUT:
Need to Serialize the class Student

Prof. Vaishali Katkar


Serialization example:
import [Link]; public String getName( )
import [Link]; {
import [Link].*; return name;
}
class Student implements Serializable public void setName(String name)
{ {
private String name; [Link]=name;
private int age; }
public int getAge( )
public Student( String name, int age) {
{ return age;
[Link]=name; }
[Link]=age; public void setAge(int age)
} {
public Student( ) [Link]=age;
{ }
} }

Prof. Vaishali Katkar


Serialization example:
OUTPUT: [Link]

OUTPUT: on Console

Prof. Vaishali Katkar


Example of Java Deserialization

• Deserialization is the process of reconstructing the object from the serialized state
• It is the reverse operation of serialization
• Let's see an example where we are reading the data from a deserialized object

Prof. Vaishali Katkar


Deserialization example:
import [Link]; public void setName(String name)
import [Link]; {
import [Link].*; [Link]=name;
}
class Student implements Serializable public int getAge( )
{ {
private String name; return age;
private int age; }
public void setAge(int age)
public Student( String name, int age) {
{ [Link]=age;
[Link]=name; }
[Link]=age; public void displayName( )
} {
public String getName( ) [Link]("Hello, My name is "+ [Link]);
{ [Link]("and My age is "+ [Link]);
return name; }
} }
Prof. Vaishali Katkar
Deserialization example:
public class Deserial
{
public static void main(String args[ ])
{
try
{
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
<

Student s1=(Student) [Link]( );


[Link]( ); OUTPUT:
[Link]([Link]( )); Hello, My name is Ankit
[Link]([Link]( )); and My age is 20
}
catch(ClassNotFoundException ex)
{
[Link]();
}
catch(IOException e)
{
[Link]( );
} } }
Prof. Vaishali Katkar
Example for Serialization in Java
The following program code will serialize a student object and save it to a file named [Link].

Prof. Vaishali Katkar


Example for Deserialization in Java
In the code below, you will look at how to deserialize the student object that was have serialized in the above
example.

Prof. Vaishali Katkar


Example for Deserialization in Java

Prof. Vaishali Katkar

You might also like