/**
* 演示功能: 序列化与反序列化
*
* 如果需要序列化 GameStatus,需要满足一下条件
* 1、实现 Serializable 接口
* 2、成员也是可以序列化的
*
* @author brian
*
*/
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;
class GameStatus implements Serializable {
/**
*
*/
private static final transient long serialVersionUID = 1L;
String user = "test";
int score = 13000;
transient String dummy = "unimportant"; // transient 不序列化
public void Show() {
System.out.println(serialVersionUID + " " + user + " " + score + " " + dummy);
}
}
public class SerializableExample1 {
/**
* 序列化
* @param obj
* @param file
*/
public static void Write(Object obj, String file) {
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close(); // 关闭 oos时,会自动关闭 fos
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 反序列化
* @param file
* @return
*/
public static Object Read(String file) {
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
obj = ois.readObject();
ois.close(); // 关闭ois时,fis也会关闭
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String file = "d:/GameStatus.ser";
GameStatus onePlay = new GameStatus();
Write(onePlay, file);
GameStatus oldPlay = (GameStatus) Read(file);
oldPlay.Show();
}
}
序列化与反序列化
最新推荐文章于 2024-07-28 19:41:52 发布