对象的序列化:将对象转换成字节序列,并可以写入文件,保存到硬盘上,ObjectOutputStream类。
对象反序列化:从文件中读取字节流,并转换成对象。ObjectInputStream类。
package com.example.javatest;
/**
* Author:W
* 玩家类对象可序列化,则需要实现接口Serializable
*/
public class Player implements java.io.Serializable{
public String name;
public int id;
public int age;
//如果有一个属性不是可序列化的,则该属性必须注明是短暂的。
public transient String tempLoginTime;
}
package com.example.javatest;//包名定义
/**
* Author:W
* 对象序列化与反序列化
* 1)序列化:ObjectOutputStream
* 2)反序列化:ObjectInputStream
*/
import java.io.*;
public class MainTest{
public static void main(String[] args)
{
String path = "G:/JavaTest/LocalFiles/Test/player.ser";
System.out.println("====Player类对象序列化====");
Player player = new Player();
player.id = 10023;
player.name = "C罗";
player.age = 34;
player.tempLoginTime ="2021-08-15";
try
{
FileOutputStream fileOutputStream = new FileOutputStream(path);
ObjectOutputStream objOut = new ObjectOutputStream(fileOutputStream);
objOut.writeObject(player);
objOut.close();
fileOutputStream.close();
System.out.println("Player对象序列化完成!路径:"+ path);
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("====Player类反序列化====");
Player player2 = null;
try
{
FileInputStream fileInputStream = new FileInputStream(path);
ObjectInputStream objInput = new ObjectInputStream(fileInputStream);
player2 = (Player)objInput.readObject();
objInput.close();
fileInputStream.close();
}catch (IOException e)
{
e.printStackTrace();
return;
}catch(ClassNotFoundException e)
{
System.out.println("Class类不存在!");
e.printStackTrace();
return;
}
System.out.println("id = "+player2.id);
System.out.println("name = "+player2.name);
System.out.println("age = "+player2.age);
System.out.println("tempLoginTime = "+player2.tempLoginTime);
}
}
运行结果如下: