Java对象序列化

时间:2023-01-02 12:04:02

最近在准备面试,复习java基础知识,记录一下Java对象的序列化:

Java对象的序列化:要想实现序列化,需要把被序列化的对象(类)实现Java.io.Serializable接口,配合FileOutputStream、FileInputStream、FileOutputStream、FileInputStream实现把对对象数据转换成二进制流存储到字旁的固定文件上,再把他读进来

代码演示:

package cn.com.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableTest {

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
SerializableTest.Serialize();
SerializableTest.deSerialize();
}

public static void deSerialize() throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("F:\\test.txt")) ;
//读取Hello
System.out.println((String)in.readObject());
//读取person
System.out.println((Person)in.readObject());
in.close();
}

public static void Serialize() throws FileNotFoundException, IOException{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("F:\\test.txt")) ;
out.writeObject("Hello!");
out.writeObject(new Person("张剑飞", 22));
out.close() ;
}

}

@SuppressWarnings("serial")
class Person implements Serializable {
private String name ;
private int age ;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}

}