java.io.Externalizable
interface
There are two methods readExternal()
and writeExternal() in Externalizable interface those can be used in serialization
process.
@Override
public void readExternal(ObjectInput arg0)
throws IOException, ClassNotFoundException { }
@Override
public void
writeExternal(ObjectOutput arg0) throws IOException { }
Externalizable interface extends
Serializable interface.
Need of Externalizable
1.If you are not happy with the way java writes/reads objects from
stream.
2.Special handling for super types on object construction during
serialization.
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class Person implements Externalizable {
private int id;
private String
name;
private String
gender;
@Override
public void writeExternal(ObjectOutput
out) throws IOException {
out.writeInt(id);
out.writeObject(name+"xyz");
out.writeObject("abc"+gender);
}
@Override
public void readExternal(ObjectInput
in)throws IOException,
ClassNotFoundException{
id=in.readInt();
//read in the same order as written
name=(String) in.readObject();
if(!name.endsWith("xyz")) {
throw new IOException("corrupted data");
} else {
name=name.substring(0, name.length()-3);
}
gender=(String) in.readObject();
if(!gender.startsWith("abc")) {
throw new IOException("corrupted data");
} else {
gender=gender.substring(3);
}
}
@Override
public String
toString(){
return "Person{id="+id+",name="+name+",gender="+gender+"}";
}
// Setters and Getters
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ExternalizationTest {
public static void main(String[] args) {
String fileName = "person.ser";
Person person = new Person();
person.setId(1);
person.setName("Pankaj");
person.setGender("Male");
try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream fis;
try {
fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Person p = (Person)ois.readObject();
ois.close();
System.out.println("Person Object Read= "+p);
} catch (IOException
| ClassNotFoundException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment