序列化与反序列化
近些天发现自己从事java开发,太多东西没有整理过,对自己也不负责,今天开始慢慢整理一些东西,这样才觉得真正掌握了.
首先我们要写一个对类,用于对象的序列化,这个类实现了Serializable接口。类的定义如下:
—start—
public class Student implements **Serializable** {
private String name;
private char sex;
private int year;
public Student() {
}
public Student(String name, char sex, int year) {
this.name = name;
this.sex = sex;
this.year = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
下面的就是序列化与反序列化主程序
–注意,追加时需要去掉头部 aced 0005
public class UseStudent {
public static void main(String[] args) throws Exception {
Student st = new Student("Melt", 'G', 25);
File file = new File("E:\\test.txt");
FileOutputStream fo = null;
ObjectOutputStream oos = null;
boolean isexist = false;//定义一个用来判断文件是否需要截掉头aced 0005的
if (file.exists()) {
isexist = true;
fo = new FileOutputStream(file, true);
oos = new ObjectOutputStream(fo);
long pos = 0;
if (isexist) {
**pos = fo.getChannel().position() - 4;//追加的时候去掉头部aced 0005
fo.getChannel().truncate(pos);**
}
oos.writeObject(st);//进行序列化
System.out.println("追加成功");
} else {
file.createNewFile();
fo = new FileOutputStream(file);
oos = new ObjectOutputStream(fo);
oos.writeObject(st);//进行序列化
System.out.println("首次对象序列化成功!");
}
oos.flush();
oos.close();
fo.close();
//反序列化
ObjectInputStream ois;
FileInputStream fn = new FileInputStream(file);
ois = new ObjectInputStream(fn);
while (fn.available() > 0) {//代表文件还有内容
Student p = (Student) ois.readObject();//从流中读取对象
//Laoshi p = (Laoshi) ois.readObject();//从流中读取对象
System.out.println(p.getName());
}
ois.close();
fn.close();
}
}
—end—
序列化对象的追加与从文件读取多个对象实就实现了.
总结:
序列化目前我一次也没有用过,哈哈不过书到用时方恨少.各位可以了解这个先