序列化是JAVA中保存对象的一种方法
Java在保存文件时一般采用将对象序列化,然后将被序列化的对象写到文件中。然后你在需要的时候对它进行解序列化把他们还原。
那么对象序列化时,对象到底经历了什么?
从实际生活上来讲,就像是一个物体被压缩了似的,但它的核心数据被完好无损的保存了起来,当你再需要用时,进行解压即可。
从程序上来看:Foo myFoo = new Foo();
myFoo.setWidth(37);
myFoo.setHeight(70);//带有两个数据
FileOutputStream fos = new FileOutputStream("foo.ser");//foo.ser这个文件如果不在就会被创建出来
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myFoo);//创建出FileOutputStream链接到ObjectOutputStream以让它写入对象
oos.close();
相当与将myFoo这个对象序列化保存在foo.ser文件中
---------------------------------------------------------------------------------------------------------------------------------
以上是最简单的例子,而需要注意的是当我们再编写程序时,应该要让它们的类也被序列化,即:
import java.io.*;//必须要引入这个包
public class Foo implements Serializable
实现Serializable接口的唯一目的就是声明实现它的类时可以被序列化的,换句话说就是此类型的对象可以通过序列化的机制来存储。
---------------------------------------------------------------------------------------------------------------------------------
将文件序列化后,当我们以后再要读取文件时,那应该怎么办呢?
这就需要用到解序列化,将对象还原。解序列化有点像序列化的反向操作。
FileInputStream fis = new FileInputStream("foo.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();//这里和序列化不同的是读取出来的是Object类,需要强制转换
Foo f = (Foo)obj;
ois.close();
附:
简单体现序列化作用的程序代码
package practice;//5.3 存储与恢复游戏人物
import java.io.*;
public class GameSaverTest {
public static void main(String[] args) {
GameCharacter one = new GameCharacter( 50 ,"Elf",new String[] {"bow","sword","dust"});
GameCharacter two = new GameCharacter( 200 ,"XXD ",new String[]{"a","b","c"});
GameCharacter three = new GameCharacter( 120 ,"TSY ",new String[]{"d","e","f"});
try{//序列化
FileOutputStream fos = new FileOutputStream("Game.ser");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(one);
os.writeObject(two);
os.writeObject(three);
os.close();
}catch(IOException ex){
ex.printStackTrace();
}
one = null;//将游戏人物数据清零,为的是体现序列化可以保存数据而不会因为数据变化而改变
two = null;
three = null;
try{//解序列化
ObjectInputStream is = new ObjectInputStream(new FileInputStream("Game.ser"));
GameCharacter oneRestore=(GameCharacter) is.readObject();
GameCharacter twoRestore=(GameCharacter) is.readObject();
GameCharacter threeRestore=(GameCharacter) is.readObject();
System.out.println(oneRestore.getPower());
System.out.println(twoRestore.getPower());
System.out.println(threeRestore.getPower());
}catch(IOException ex){
ex.printStackTrace();
}catch(ClassNotFoundException ex){
ex.printStackTrace();
}
}
}
class GameCharacter implements Serializable{//创建需要保存的类,实现启动序列化的接口
int power;
String type;
String[] weapons;
public GameCharacter(int p ,String t,String[] w){
power = p;
type = t;
weapons =w;
}
public int getPower(){
return power;
}
public String getType(){
return type;
}
public String getWeapons(){
String weaponList = " ";
for(int i=0 ;i<weapons.length;i++)
weaponList += weapons[i];
return weaponList;
}
}