I am exploring on externalizable interface. I found a strange behaviour when I wrote more property in serialized file than what I read. Below is my employee class.
public class Employee implements Externalizable {
private int id;
private String name;
private Boolean isTempEmp;
public Employee(int id, String name, Boolean isTempEmp) {
super();
this.id = id;
this.name = name;
this.isTempEmp = isTempEmp;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", isTempEmp=" + isTempEmp + "]";
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id);
out.writeUTF(name);
out.writeBoolean(isTempEmp);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.id=in.readInt();
this.name=in.readUTF();
//this.isTempEmp=in.readBoolean();
}
}
And Below is my class for externalizing employee object in file and read from the file
public class ExternalizeTest2 {
public static void main(String[] args) {
Employee emp1=new Employee(1, "Swet", true);
Employee emp4=new Employee(2, "Varun", true);
try(OutputStream os=new FileOutputStream("Employee.txt");
ObjectOutputStream oos=new ObjectOutputStream(os);) {
emp1.writeExternal(oos);
emp4.writeExternal(oos);
}catch (Exception e) {
e.printStackTrace();
}
Employee emp2=new Employee(3, "Test1", false);
Employee emp3=new Employee(4, "Test2", false);
try(InputStream is=new FileInputStream("Employee.txt");
ObjectInputStream ois=new ObjectInputStream(is);) {
emp2.readExternal(ois);
emp3.readExternal(ois);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("After externalization: \n"+emp2.toString());
System.out.println(emp3.toString());
}
}
Below is the output I am getting:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.readByte(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTFChar(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(Unknown Source)
at java.io.ObjectInputStream.readUTF(Unknown Source)
at serialization.externalize.Employee.readExternal(Employee.java:40)
at serialization.externalize.ExternalizeTest2.main(ExternalizeTest2.java:32)
After externalization:
Employee [id=1, name=Swet, isTempEmp=false]
Employee [id=16777216, name=Test2, isTempEmp=false]
Not sure how id assigned to emp3 is 16777216.