:定义自己的类MyObject继承ObjectOutputStream
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class MyObject extends ObjectOutputStream{
protected MyObject() throws SecurityException, IOException{
super();
}
//文件每次写入都会写入文件头,使用自己的定义的类使writeStreamHeade方法不写入头部
@Override
protected void writeStreamHeader() throws IOException {
// TODO Auto-generated method stub
}
public MyObject(OutputStream o) throws IOException{
super(o);
}
}
:序列化存入与反序列化读出
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class TestObjekt {
public void yanzhen() throws IOException{
//使用键盘录入对象
Scanner sc=new Scanner(System.in);
String name=sc.next();
int age=sc.nextInt();
sc.close();
//创建File对象
File f=new File("a.obj");
FileOutputStream fo=null;
ObjectOutputStream ob=null;
MyObject mb=null;
Student stu=new Student(name,age);
//当文件中无内容,使用原有的ObjectOutputStream存入对象
if(f.length()==0) {
fo=new FileOutputStream(f,true);
ob=new ObjectOutputStream(fo);
ob.writeObject(stu);
//当文件中有内容,使用自己定义的ObjectOutputStream继承类存入对象
}else {
fo=new FileOutputStream(f,true);
mb=new MyObject(fo);
mb.writeObject(stu);
}
if(mb!=null) {
mb.close();
}
if(ob!=null) {
ob.close();
}
fo.close();
}
public void cha(){
FileInputStream fi=null;
ObjectInputStream ib=null;
try {
fi=new FileInputStream("a.obj");
ib=new ObjectInputStream(fi);
Student st;
while((st=(Student)ib.readObject())!=null) {
System.out.println(st.getName());
}
//readObject读到最后时不会返回null只会抛出异常使用catch捕获异常
}catch(EOFException e) {
}catch(IOException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}finally {
//当为空文件时不会new一个ib对象需要先判断,负责报错
try {
if(ib!=null) {
ib.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(fi!=null) {
fi.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws ClassNotFoundException, IOException{
TestObjekt t=new TestObjekt();
t.yanzhen();
t.cha();
}
}