对象的序列化和反序列化:
1、对象的序列需要实现java.util.Serializable或者是java.io.Externalizable接口。
2、Serializable只是一个接口,代表着可序列化,并没有定义任何的抽象方法,只能序列化非静态的,以及没有使用transient关键字修饰的属性,使用此接口最好声明一 个“private static final long serialVersionUID = 1L;”常量,确保在类的修改等操作之后,也能够反序列化
3、其中Externalizable接口继承Serializable接口,可以自定义序列化、反序列化的属性(包含静态属性和transient的),此接口多出了两个抽象方法
writeExternal(ObjectOutput out) throws IOException :用于自定义需要序列化的属性
writeExternal(ObjectOutput out) throws IOException :用于自定义需要反序列化的属性
4、另一个try(){}...catch(){}finally{}...,这种try...catch可以自动关闭资源,省去了手动关闭的麻烦
try(括号中放需要关闭的资源类代码){此括号中放逻辑代码}catch(异常){}finally{}
示例:
package javase.day23;
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class TestExternalizable {
public static void main(String[] args) {
//自1.7之后的另一个try(){}...catch(){}...
try(
FileOutputStream fos = new FileOutputStream("student.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("student.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
){
Student student = new Student("tom");
Student.school = "二中";
student.setAge(18);
oos.writeObject(student);
Student stu = (Student) ois.readObject();
System.out.println(stu);
}catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student implements Externalizable{
private transient String name;
public static String school = "一中";
private int age;
public Student() {
super();
}
public Student(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age = " + age + ", school = " + school + "]";
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeUTF(school);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF();
school = in.readUTF();
}
}
原文地址:https://www.cnblogs.com/dirsoen/p/12625443.html