若要类能被序列化要实现serializable借口。
我自己理解的序列化与反序列化:
序列化:将对象的值写入Txt或者ser文件当中,对象可以以文本的方式进行存储。写入后对象为空。
反序列化:将Txt文件或者ser文件读取,将其值按照对应关系赋给对象。
其中student类在另一文件中定义,定义如下:
String id;
String name;
String score;
void set(String id,String name,String score){
this.id=id;
this.name=name;
this.score=score;
}
代码:
package home;
import java.io.*;
public class Xuliehua {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student one=new Student();
one.set("141114101","dupangzi","11");
Student two=new Student();
two.set("141114102","jiangshouzi","99");//innitialize object
try(ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("D://1.ser"))){
os.writeObject(one);
os.writeObject(two);
System.out.println("job done!");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
此时1.ser文件增加两行内容
2.反序列化
反序列化:从foo.ser 里面读出对象,通过强制类型转化为student类
package home;
import java.io.*;
public class ReadSer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try ( final ObjectInputStream is = new ObjectInputStream(new FileInputStream("D://foo.ser"))) {
while (true)
{
Student oneStu=(Student)is.readObject();
Student twoStu=(Student)is.readObject();
System.out.println(oneStu.id + " " + oneStu.name + " "+ oneStu.score);
System.out.println(twoStu.id + " " + twoStu.name + " "+ twoStu.score);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}