1. Problem:
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?
2. Serialization and Deserialization
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
3, serialization and deserialization
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.
2. Achieve remote network communication , using serialization, the byte sequence of the object can be transmitted over the network.
4. Benefits of serialization and deserialization
1. Achieve data persistence and permanently save data on the local hard disk through serialization;
5.1. Implement Serializable interface
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 省略。。。*/
}
5.2. ObjectOutputStream and ObjectInputStream The Serializalable interface only provides a representation to convert objects into binary sequences and restore binary sequences into objects. There are two methods provided by ObjectOutputStream and OjbectInputStream: writeObject() and 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(); }
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;
}
6, transientOn 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);
Deserialization, the read object found: sex is null, indicating that it is transient Modified properties will not be serialized.

- 1. Remove the modification of transient
- 2. Provide two methods
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:
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?
2、序列化与反序列化
Java序列化:将对象转为字节的过程,这正好符合我的需求。
Java反序列化:将字节恢复为对象的过程
这满足我们想文件中写对象,和读取对象
3、序列化和反序列化的使用场景
a、将对象写道硬盘中;
b、网络间传输
当在网络上传送文本,音频,视频等,都是转化为二进制序列传送,我们要在网络上传送对象,就必须使用序列化和反序列化,满足数据的发送和接收。
###4、序列化和反序列化的好处
一、实现数据的持久化,通过序列化将数据永久的保存在本地的硬盘上;
二、实现远程网络通信,利用序列化,使得在网络上可以传输对象的字节序列。
5、如何实现序列化和反序列化
5.1 、实现Serializable接口
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 省略。。。*/ }
5.2、ObjectOutputStream与ObjectInputStream
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; }
6、transient
在某种场合,我们对某些敏感字段不要进行序列化,或者类的引用类型的成员不能够进行序列化, 这是我们需要使用transient来修饰这些成员, 以避免它们被序列化。如:银行账户对象,不希望对账户金额进行序列化。
修改上面的Student类,将sex属性使用transient修饰
transient private String sex;
再进行序列化
Student s1 = new Student("roase",19, "女"); write(s1);
反序列化, 读取的对象发现:sex为null,说明被transient修饰的属性不会被序列化。
6.1 defaultWriteObject和defaultReadObject()
对于上面的被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)!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
