概念
-
Java进程通信的时候使用序列化实现对象之间的传递。
应用场景
-
永久性保存对象,保存对的字节序列到本地文件或者数据库中
-
通过序列化以字节流的形式对象在网络中进行传递和接收
-
通过序列化在进程间传递对象
好处
-
实现了数据的持久化,通过序列化可以把数据永久地保存到硬盘上
-
利用序列化实现远程通信,即在网络上传送对象的字节序列
实体类
/**
* 让类实现Serializable保证其可以被序列化来传递参数
*/
public class User implements Serializable {
private String username;
private String sex;
private transient Integer age;
// 省略所有的Set()与Get()方法 以及 无参有参构造函数
}
写文件
public class Write {
public static void main(String[] args) {
User u = new User("张三","男",18);
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
// 将用户写入user.txt中
fileOutputStream = new FileOutputStream("user.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(u);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
读文件
public class Read {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
try {
fileInputStream = new FileInputStream("user.txt");
objectInputStream = new ObjectInputStream(fileInputStream);
User u = (User) objectInputStream.readObject();
System.out.println("Username:" + u.getUsername()); // Username:张三
System.out.println("Sex:" + u.getSex()); // Sex:男
System.out.println("Age:" + u.getAge()); // Age:null
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
测试结果
可以看到Age属性是没有值的,是因为用到了transient关键字。它的作用是控制变量的序列化,可以阻止该变量被序列化到文件中。最终会输出数据类型的初始值。
serialVersionUID
这里也需要介绍一下关于序列化ID。如果读取文件的序列化ID不同,那么就无法做到读文件。是在实体类中加入下行代码。当然后面的常量值根据公司要求去设置。
private static final long serialVersionUID = 123456L;