Home >Java >javaTutorial >JAVA serialization
If you want to write an object to a file, you find that neither the byte stream nor the character stream can meet the requirements. How to write objects to a file?
When using the byte character stream, you must convert the object into bytes/characters and then write it to the file. However, the byte character stream does not have a method for converting the object into bytes. How to do this?
Java serialization: the process of converting objects into bytes, which exactly meets my needs.
Java deserialization: the process of restoring bytes to objects
This satisfies the usage scenarios of writing objects in files and reading objects
a. Write the object to the hard disk;
b. Transfer between networks
When text, audio, video, etc. are transmitted over the network, they are converted into binary sequences for transmission. If we want to transmit objects over the network, we must use serialization and deserialization to meet the sending and receiving of data.
4. Benefits of serialization and deserialization
1. Achieve data persistence and permanently save data on the local hard disk through serialization;
Serializable interface There is no method, it just provides an identifier to tell the java mechanism that the class can be serialized;
If this identifier is not created, the java mechanism will automatically create one. SerialVersionUID generates a 64-bit hash field based on the class name, interface name, member method and attribute
If there is no SerialVersionUID, usually we will find that if the attributes of the class are modified after serialization, an error will be reported during deserialization, because the tired attributes have been modified, java The mechanism will re-create a SerialVersionUID, resulting in inconsistency with the original ID and deserialization failure.
If the implementation SerialVersionUID is set to ensure version compatibility, even if attributes or methods are added, serialization and deserialization can still be performed, Only the value of the newly added attribute is null, or the value of the deleted attribute is not displayed.
package com.chb.test;import java.io.Serializable;public class Student implements Serializable{ //序列化标识 private static final long serialVersionUID = 1L; private String name; private int age; private String sex; public Student() { } public Student(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Student{" +"姓名:"+this.name +"性别:"+this.sex +"年龄"+this.age + "}"; } /**setter getter 省略。。。*/ }
public static void write(Student s1) throws Exception { FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(s1); oos.close(); }
public static Student read() throws Exception { FileInputStream fis = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fis); Student stu = new Student(); //使用readeObject()进行反序列化 stu= (Student) ois.readObject(); ois.close(); return stu; }
On certain occasions, we do not want to serialize certain sensitive fields, or members of reference types of classes Serialization is not possible. This is why we need to use transient
to modify these members to prevent them from being serialized. For example: bank account object, you do not want to serialize the account amount.
transient private String sex;and then serialize
Student s1 = new Student("roase",19, "女"); write(s1);
private void writeObject(ObjectOutputStream out) throws Exception{ out.defaultWriteObject(); out.writeInt(age); } private void readObject(ObjectInputStream in) throws Exception { in.defaultReadObject(); age=in.readInt(); }In the writeObject() method, the defaultWriteObject() method in ObjectOutputStream will be called first. This method will execute the default serialization mechanism, and the age field will be ignored. Then call the writeInt() method to explicitly write the age field to the ObjectOutputStream. The function of readObject() is to read objects, and its principle is the same as the writeObject() method. Execute the read() application again, and the following output will appear: 1. Question:
If you want to write an object to a file , found that neither the byte stream nor the character stream can meet the requirements. How to write objects to a file?
Java序列化:将对象转为字节的过程,这正好符合我的需求。
Java反序列化:将字节恢复为对象的过程
这满足我们想文件中写对象,和读取对象
a、将对象写道硬盘中;
b、网络间传输
当在网络上传送文本,音频,视频等,都是转化为二进制序列传送,我们要在网络上传送对象,就必须使用序列化和反序列化,满足数据的发送和接收。
###4、序列化和反序列化的好处
一、实现数据的持久化,通过序列化将数据永久的保存在本地的硬盘上;
二、实现远程网络通信,利用序列化,使得在网络上可以传输对象的字节序列。
Serializable接口没有任何方法,只是提供一个标识 , 用来告诉java机制该类可以被序列化;
如果没有创建这个标识,java机制将会自动的创建一个,SerialVersionUID是根据类名, 接口名,成员方法及属性等来生成一个64位哈希字段。
如果没有SerialVersionUID, 通常我们会发现,如果在序列化后,修改了类的属性, 在进行反序化,会报错,因为累的属性修改了,java机制会重新创建一个SerialVersionUID, 导致与原来的ID不一致, 反序列化失败。
如果设置了实现SerialVersionUID, 保证版本的兼容性, 即使添加了属性或方法, 仍然能进行序列化和反序列化, 只是新添加的属性值为null,或不显示被删除属性的值。
package com.chb.test;import java.io.Serializable;public class Student implements Serializable{ //序列化标识 private static final long serialVersionUID = 1L; private String name; private int age; private String sex; public Student() { } public Student(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Student{" +"姓名:"+this.name +"性别:"+this.sex +"年龄"+this.age + "}"; } /**setter getter 省略。。。*/ }
Serializalable接口只是提供一个表示,将对象转为二进制序列,和二进制序列恢复成对象是由ObjectOutputStream和OjbectInputStream提供的两个方法:writeObject()和readObject()
writeObject()
public static void write(Student s1) throws Exception { FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(s1); oos.close(); }
readObject()
public static Student read() throws Exception { FileInputStream fis = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fis); Student stu = new Student(); //使用readeObject()进行反序列化 stu= (Student) ois.readObject(); ois.close(); return stu; }
在某种场合,我们对某些敏感字段不要进行序列化,或者类的引用类型的成员不能够进行序列化, 这是我们需要使用transient来修饰这些成员, 以避免它们被序列化。如:银行账户对象,不希望对账户金额进行序列化。
修改上面的Student类,将sex属性使用transient修饰
transient private String sex;
再进行序列化
Student s1 = new Student("roase",19, "女"); write(s1);
反序列化, 读取的对象发现:sex为null,说明被transient修饰的属性不会被序列化。
对于上面的被transient的成员age, 如果我们想让它能够在此序列化和反序列化,要如何做:
1、去掉transient的修饰
2、提供两个方法
private void writeObject(ObjectOutputStream out) throws Exception{ out.defaultWriteObject(); out.writeInt(age); } private void readObject(ObjectInputStream in) throws Exception { in.defaultReadObject(); age=in.readInt(); }
在writeObject()方法中会先调用ObjectOutputStream中的defaultWriteObject()方法,该方法会执行默认的序列化机制,此时会忽略掉age字段。然后再调用writeInt()方法显示地将age字段写入到ObjectOutputStream中。readObject()的作用则是针对对象的读取,其原理与writeObject()方法相同。再次执行read()应用程序,则又会有如下输出:
以上就是JAVA之序列化的内容,更多相关内容请关注PHP中文网(www.php.cn)!