JAVA_序列化与反序列化实践
package com.lius.DistributedProject.RPC.rpc_java; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * java序列化实践 * @author lius * */ public class serielizeObject { //序列化 public static byte[] SerializeObject(Object obj) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); byte[] resultByte = baos.toByteArray(); return resultByte; } //反序列化 public static Object reverseSerializeObject(byte[] byteObject) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(byteObject); ObjectInputStream ois = new ObjectInputStream(bais); Object obj = ois.readObject(); return obj; } public static void main(String[] args) throws IOException, ClassNotFoundException { //创建对象 student student1 = new student("tom", 18); student1.print(); //序列化对象 byte[] bytes = SerializeObject(student1); //反序列化对象 student1 = (student) reverseSerializeObject(bytes); student1.print(); } public static class student implements Serializable{ private String name; private int age; public student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "student [name=" + name + ", age=" + age + "]"; } public void print() { System.out.println(toString()); } } }
JAVA_序列化与反序列化实践
最新推荐文章于 2023-04-15 09:48:19 发布