对象流
java.io.StreamCorruptedException: invalid type code: AC问题解决 代码片
.
package com.bangkeju.fileio;
/**
* 测试使用ObjectInputStream ObjectOutputStream 进行读写对象进文件 对象必须序列化 处理流
*/
import java.io.*;
public class TestObjectInputStream {
public static void main(String[] args) {
File file1 = new File("d:/a/dataobject1.txt");
int flag;
// flag=write(file1);
flag = read(file1);
}
private static int write(File file1) {
ObjectOutputStream dos = null;
try {
dos = new ObjectOutputStream(new FileOutputStream(file1,true));//对象流 处理流
// dos.writeInt(12);//ObjectOutputStream 也可以对基本类型进行 写
// dos.writeBoolean(true);
// dos.writeDouble(3.14);
// dos.writeUTF("bangkeju");
/*dos.writeObject(new Student(11,"liu","男",98));//类没修过之前的构造方法
dos.writeObject(new Student(11,"xiao","男",98));
dos.writeObject(new Student(11,"gang","男",98));*/
dos.writeObject(new Student(13,"liu","男",98,23));//Student修改之后的构造方法
dos.writeObject(new Student(14,"xiao","男",98,34));
dos.writeObject(new Student(15,"gang","男",98,19));
return 1;
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
try {
if (dos != null) {
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static int read(File file) {
ObjectInputStream ois = null;
FileInputStream fis=null;
try {
// ois = new ObjectInputStream(new FileInputStream(file));
/*System.out.println(ois.readInt());//ObjectInputStream 也可以对基本类型进行读写
System.out.println(ois.readBoolean());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());*/
Object o=null;
/*while((o= ois.readObject())!=null){//读行到最后报异常,不通
System.out.println(o.toString());
}*/
//重写while循环,通过异常判断结束,但读不了追加的,报异常
/* while(true){
try {
o=ois.readObject();
System.out.println(o.toString());
} catch (EOFException e) {
break;//这是退出的条件:抛EOFException
} catch (ClassNotFoundException e) {
continue;
}
}*/
//继续重写while循环:应对追加写入的情况,此时就要把ObjectInputStream时的FileInputStream提出来
//应对每对象流每次只追加一条,同一个输出流连续追加两条则不行!
fis=new FileInputStream(file);
while(fis.available()>0){
// System.out.println(fis.available());//用于测试
ois = new ObjectInputStream(fis);//分开写有好处
try {
o=ois.readObject();
System.out.println(o.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 最彻底的解决办法就是定义一个类继承ObjectInputStream 重写 writeStreamHeader()方法 网上有参考
* */
/*System.out.println(o= ois.readObject());//一条一条都太笨重
System.out.println(o= ois.readObject());
System.out.println(o= ois.readObject());*/
// System.out.println(ois.available());
return 1;
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
}
}
;