1.序列化:
将java对象转化为字节序列
2.反序列化:
将字节序列恢复成java对象
3.序列化是干什么的:
1.保存在内存中的对象的状态
2.方便传输,实现对象的字节序列传输,如图像,视频等
4.实现
java提供两种方式一种是实现Serializable接口,另一种是实现Exteranlizable接口,使用Serializable时可利用transient关键子修饰不需要被反序列化的属性,使用Exteranlizable接口时需要重写writeExternal和readExternal方法
user类实现Serializable接口,实际为空接口,作为可反序列化标识
import java.io.Serializable; public class User implements Serializable { private String Name; private int age; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String name, int age) { Name = name; this.age = age; } }
Exteranlizable类继承了Serializable需要实现writeExternal和readExternal方法,注意使用此方法时,若类没有默认构造函数会报错
import java.io.*; public class User implements Externalizable { private String Name; private int age; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(){ } public User(String name, int age) { Name = name; this.age = age; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(Name); out.writeObject(age); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { Name = (String) in.readObject(); age = (int) in.readObject(); } }
objectOutputStream 对象输出流 objectInputStream 对象输入流
FileOutputStream 文件输出流 FileInputStream 文件输入流
利用两者将对象的序列化数据写入文件,再从文件中读取序列化数据利用readObject恢复成对象
test类代码如下:
import java.io.*; public class test { public static void main(String[] args) throws IOException,ClassNotFoundException{ Serialize(); DeSerializ(); } private static void Serialize() throws IOException { FileOutputStream fos = new FileOutputStream("D://java test//Serial//1.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); User user1=new User("xxx",21); oos.writeObject(user1); System.out.print(oos); oos.flush(); oos.close(); } private static void DeSerializ() throws IOException, ClassNotFoundException { FileInputStream fis=new FileInputStream("D://java test//Serial//1.txt"); ObjectInputStream ois=new ObjectInputStream(fis); System.out.print(ois+"\n"); User user2=(User) ois.readObject(); System.out.print(user2.getName()+user2.getAge()); } }
运行Serialize()在1.txt中保存序列化数据
运行DeSerializ()将序列化数据反序列化为对象