序列化(ObjectOutputStream): 序列化是把对象的状态信息转化为可存储或传输的形式过程,也就是把对象转化为字节序列的过程称之为对象的序列化。
序列化的对象需要实现接口:Serializable
反序列化(ObjectInputStream): 反序列化是序列化的逆向过程,把字节数组反序列化为对象,把字节序列恢复为对象的过程称为对象的反序列化。
将要被序列化的对象:
public class User implements Serializable {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}
序列化:
//序列化
public void output(){
//ObjectOutputStream 实现对象的序列化
try(
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("E:/zhangsan"));
){
User user = new User("张三",18);
//实现对象的序列化
objectOutputStream.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
}
}
反序列化:
//反序列化
public static void input(){
try(
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("E:/zhangsan"))
){
User user = (User)objectInputStream.readObject();
System.out.println(user.getName()+"-"+user.getAge());
}catch(IOException|ClassNotFoundException e){
e.printStackTrace();
}
}