对象序列化
让我们举个例子来更好地理解这些概念:
此类实现Serializable接口,这意味着可以对其进行序列化。此类中的所有字段都可以在转换为字节流之后写入文件中,除非那些字段声明为transient。在下面的示例中,我们有两个临时字段,这些字段将不参与序列化。
import java.io.Serializable;
@SuppressWarnings("serial")
public class Student implements Serializable {
private int stuRollNum;
private int stuAge;
private String stuName;
private transient String stuAddress;
private transient int stuHeight;
public Student(int roll, int age, String name, String address, int height) {
this.stuRollNum = roll;
this.stuAge = age;
this.stuName = name;
this.stuAddress = address;
this.stuHeight = height;
}
public int getStuRollNum() {
return stuRollNum;
}
public void setStuRollNum(int stuRollNum) {
this.stuRollNum = stuRollNum;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuAddress() {
return stuAddress;
}
public void setStuAddress(String stuAddress) {
this.stuAddress = stuAddress;
}
public int getStuHeight() {
return stuHeight;
}
public void setStuHeight(int stuHeight) {
this.stuHeight = stuHeight;
}
}
对象的序列化
将类Student类的对象写入Student.ser文件。我们正在使用FileOutputStream和ObjectOutputStream将对象写入文件。
注意:根据Java序列化的最佳做法,文件名应具有.ser扩展名。
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SendClass
{
public static void main(String args[])
{
Student obj = new Student(101, 25, "Chaitanya", "Agra", 6);
try{
FileOutputStream fos = new FileOutputStream("Student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
System.out.println("Serialzation Done!!");
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
上面例子输出:Serialzation Done!!