How to use the deserialization function in Java to achieve serialization and deserialization of objects
Serialization is to convert objects into objects that can be transmitted over the network or stored in The process of using a byte stream, and deserialization is the process of converting a byte stream back into an object. Java provides serialization and deserialization mechanisms so that developers can easily store and transmit objects. This article will introduce how to use the deserialization function in Java to serialize and deserialize objects, and give specific code examples.
Sample code:
import java.io.Serializable; public class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } // getter and setter }
Sample code:
import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class SerializationDemo { public static void main(String[] args) { Person person = new Person("张三", 25); try { FileOutputStream fileOut = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); out.close(); fileOut.close(); System.out.println("对象已被序列化并保存在person.ser文件中"); } catch (Exception e) { e.printStackTrace(); } } }
Sample code:
import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializationDemo { public static void main(String[] args) { Person person = null; try { FileInputStream fileIn = new FileInputStream("person.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); person = (Person) in.readObject(); in.close(); fileIn.close(); } catch (Exception e) { e.printStackTrace(); } if (person != null) { System.out.println("对象已经从person.ser文件中反序列化:" + person.getName() + "," + person.getAge()); } } }
The above is the method and code example of using the deserialization function to achieve serialization and deserialization of objects in Java. By implementing the Serializable interface and using the ObjectInputStream and ObjectOutputStream classes, we can easily serialize objects to byte streams, or deserialize byte streams back to objects. This mechanism has great application value in both network transmission and file storage.
The above is the detailed content of How to use the deserialization function to implement serialization and deserialization of objects in Java. For more information, please follow other related articles on the PHP Chinese website!