|
|||||
Web
Design & Development CS506
VU
Lesson
22
Serialization
What?
. You
want to send an object to a
stream.
Motivation
A lot
of code involves boring
conversion from a file to
memory
As
you might recall that
AddressBook program reads
data from file and
then parses it
This
is a common problem
Revisiting
AddressBook
We
read record from a text file
named persons.txt. The person record
was present in the file in
the
following
format.
persons.txt
The
code that was used to
construct Person objects after reading
information from the file is
given below.
Here
only the part of code is shown,
for complete listing, see
AddressBook code in your
earlier handout.
FileReader
fr = new FileReader("persons.txt");BufferedReader br =
new
BufferedReader(fr);
String
line = br.readLine();
while
( line != null ) {
tokens =
line.split(",");
name
= tokens[0];
add =
tokens[1];
ph =
tokens[2];
PersonInfo
p = new PersonInfo(name, add, ph); //
you can add p into
arraylist, if
needed
line = br.readLine();
}
As
you have seen a lot of parsing
code is required for
converting a line into
PersonInfo objects.
Serialization
mechanism eases developer's
life by achieving all above in a
very simple way.
Serialization in
Java
Java
provides an extensive support for
serialization
Object
knows how to read or write
themselves to streams
Problem:
As
you know, objects get created on
heap and have some values therefore
Objects have some state
in
memory
You
need to save and restore
that state.
The
good news is that java
serialization takes care of it
automatically
Serializable
Interface
By
implementing this interface a
class declares that it is
willing to be read/written by
automatic
serialization
machinery
Found
in java.iopackage
Tagging
interface has no methods and
serves only to identify the
semantics of being
serializable
Automatic
Writing
System
knows how to recursively
write out the state of an
object to stream
If an
object has the reference of another
object, the java serialization
mechanism takes care of
it
and
writes it too.
163
Web
Design & Development CS506
VU
Automatic
Reading
System
knows how to read the data
from Stream and re-create
object in memory
The
recreated object is of type
"Object" therefore Down-casting is
required to convert it into
actual
type.
Serialization:
How it works?
To
write an object of PersonInfo,
ObejctOutputStream and its method writeObject( )
will be used
PersonInfo
p = new PersonInfo( );
ObejctOutputStream
out;
//
writing PersonInfo's object
p
out.writeObject(p);
To
read that object back,
ObejctInputStream and its method
readObject()will be used
ObejctInputStream
in;
//
reading PersonInfo's object.
Remember type casting// is
required
PersonInfo
obj =
(PersonInfo)in.readObject( );
Example
Code 22.1: Reading / Writing PersonInfo
objects
We
want to send PersonInfo
object to stream. You have
already seen this class
number of times before.
Here
it will also implement
serializable interface.
PersonInfo.java
import
javax.swing.*;
import
java.io.*
class
PersonInfo implements Serializable{
String
name;
String
address;
String
phoneNum;
//parameterized
constructorpublic PresonInfo(String n,
String a, String p) {
name
= n;
address
= a;
phoneNm
= p;
}
//method
for displaying person record on
GUIpublic void printPersonInfo( )
{
JOptionPane.showMessageDialog(null
,
"name:
" + name + "address:" +address
+
"phone
no:" + phoneNum);
}
} //
end class
WriteEx.java
The
following class will
serialize PersonInfo object to a
file
import
java.io*;
public
class WriteEx{
public
static void main(String args[ ]){
PersonInfo
pWrite =new PersonInfo("ali",
"defence", "9201211");
try
{
//
attaching FileOutput stream
with "ali.dat"
FileOutputStream
fos =new
FileOutputStream("ali.dat");
//
attaching ObjectOutput stream
over FileOutput//
stream
ObjectOutputStream
out =new ObjectOutputStream(fos);
//serialization
164
Web
Design & Development CS506
VU
//
writing object to
`ali.dat'
out.writeObject(pWrite);
//
closing streams
out.close();
fos.close();
}
catch (Exception ex){
System.out.println(ex)
}
} //
end class
ReadEx.java
The
following class will read
serialized object of PersonInfo
from file i.e
"ali.data"
import
java.io*; public class
ReadEx{ public
static
void main(String args[ ]){ try {
//
attaching
FileInput stream with
"ali.dat"
FileInputStream
fin = new
FileInputStream("ali.dat");
//
attaching FileInput stream
over ObjectInput
stream
ObjectInputStream
in = new
ObjectInputStream(fis);
//de-serialization
//
reading object from
`ali.dat'
PersonInfo pRead =
(PersoInfo)in.ReadObject( );
//
calling printPersonInfo method to confirm
that// object contains same
set of values
before//
serializatoion
pRead.printPersonInfo();
//
closing streams
in.close();
fis.close();
}
catch (Exception ex){
System.out.println(ex)
}
} //
end class
Compile
& Execute
After
compilation, first run the
WriteEx.java file and visit the
"ali.dat" file. Then run
ReadEx.java from
different
command or same command
prompt.
Object
Serialization & Network
. You
can read / write to a
network using sockets
. All
you need to do is attach
your stream with socket
rather than file
. The
class version should be same
on both sides (client &
network) of the network
Example
Code 22.2: Sending/Reading
Objects to/from
Network
We
are going to use same
PersonInfo class listed in
example code 22.1. An object
of PersonInfo class
will
be
sent by client on network
using sockets and then be
read by server from
network.
Sending
Objects over
Network
The
following class ClientWriteNetEx.java
will send an object on
network
import
java.net.*;import java.io.*;import
javax.swing.*;
public
class ClientWriteNetEx{ public static
void
main(String
args[]){ try { PersonInfo p =
new
PersonInfo("ali",
"defence", "9201211"); // create
a
165
Web
Design & Development CS506
VU
communication
socket
Socket
s = new Socket("localhost",
2222);
//
Get I/O streams
OutputStream
is = s.getOutputStream();
//
attaching ObjectOutput stream
over Input stream
ObjectOutputStream
oos= new
ObjectOutputStream(is);
//
writing object to
network
oos.write(p);
//
closing communication
socket
s.close();
}catch(Exception
ex){
System.out.println(ex);
}
} }//
end class
Reading
Objects over
Network
The
following class ServerReadNetEx.java
will read an object of
PersonInfo sent by
client.
import
java.net.*;import java.io.*;import
javax.swing.*;
public
class ServerReadNetEx{
public
static void main(String
rgs[])
{
try
{
//
create a server
socket
ServerSocket
ss = new ServerSocket(2222);
System.out.println("Server
started...");
/*
Loop back to the accept method of the
serversocket and wait for a
new connection
request.
Soserver
will continuously listen for
requests
*/
while(true)
{
//
wait for incoming
connection
Socket
s = ss.accept();
System.out.println("connection
request recieved");
//
Get I/O streams
InputStream
is = s.getInputStream();
//
attaching ObjectOutput stream
over Input stream
ObjectInputStream
ois = new
ObjectInputStream(is);
//
read PersonInfo object from
network
PersonInfo p =
(PersonInfo)ois.read( );
p.printPersonInfo();
//
closing communication
socket
s.close();
} // end
while
}catch(Exception
ex){ System.out.println(ex); } } } // end
class
Compile
& Execute
After
compiling both files, run
ServerReadNetEx.java first, from the
command prompt window.
Open
another
command prompt window and
run ClientWriteNetEx.javafrom
it.
The
ClientWriteNetEx.java will send an
Object of PersonInfo to
ServerReadNetEx.java that displays
that
object
values in dialog box after
reading it from
network.
Preventing
Serialization
Often
there is no need to serialize sockets,
streams & DB connections etc because
they do no
represent
the state of object, rather connections to
external resources
166
Web
Design & Development CS506
VU
To do
so, transient
keyword
is used to mark a field that
should not be
serialized
So we
can mark them as,
o
transient
Socket
s;
o
transient
OutputStream
os;
o
transient
Connecction
con;
Transient
fields are returned as
nullon reading
Example
Code 22 . 3: transient
Assume
that we do not want to
serialize phoneNum attribute of
PersonInfo class, this can
be done as shown
below
PersonInfo.java
import
javax.swing.*;
import
java.io.*
class
PersonInfo implements Serializable{
String
name;
String
address;
transient
String
phoneNum;
public
PresonInfo(String n, String a, String p)
{ name = n;address = a;phoneNm =
p;
}
public
void printPersonInfo( ) {
JOptionPane.showMessageDialog(null
, "name: " + name + "address:"
+address +
"phone
no:" + phoneNum);
}
} //
end class
References
Entire
material for this handout is
taken from the book JAVA A
Lab Course by Umair
Javed.
This
material
is available just for the
use of VU students of the course Web
Design and Development and not
for
any
other commercial purpose without the
consent of author.
167
Table of Contents:
|
|||||