日期:2014-05-20  浏览次数:20947 次

对象ObjectInputStream的文件操作,报java.io.StreamCorruptedException异常。
我在给文件了写对象,每次写三个QQ对象,每次写得是追加在原来的后面的。写是正常的,但当我从文件中读对象时,只能读到第一次写得,就报下面的异常:
java.io.StreamCorruptedException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1332)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at test.main(test.java:24)
谁能帮我解决,加20分,好的话还可以多加。谢谢。
我的代码如下:
文件1:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.qq.server.QQ;


public class test2 {
public static void main(String[] args) {
FileOutputStream fos=null;
ObjectOutputStream oos=null;

try {
File file=new File("QQ1.txt");
fos=new FileOutputStream(file,true);
oos=new ObjectOutputStream(fos);
QQ qq=new QQ(1,"231","fds","fds","sadf",3213,"fdsaf","fdsafsd");
QQ qq1=new QQ(1,"231","fds","fds","sadf",3213,"fdsaf","fdsafsd");
QQ qq2=new QQ(1,"231","fds","fds","sadf",3213,"fdsaf","fdsafsd");
oos.writeObject(qq);
oos.writeObject(qq1);
oos.writeObject(qq2);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(oos!=null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

}
文件2:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import com.qq.server.QQ;

public class test {

/**
* @param args
*/
public static void main(String[] args) {
FileInputStream fis = null;
ObjectInputStream ois = null;

try {
File file = new File("QQ.txt");
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
QQ qq = null;
while ((qq = (QQ) ois.readObject()) != null) {

System.out.println("qq:" + qq);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



}

}
文件3:
package com.qq.server;

public class QQ implements java.io.Serializable{
private int id;
private String nickname;
private String name;
private String passwd;
private String rpasswd;
private double tel;
private String mail;
private String Signed;
private static final long serialVersionUID = 123456789l;
public QQ(){

}
public QQ(int id, String nickname, String name, String passwd,String rpasswd, double tel, String mail, String signed) {
super();
this.id = id;
this.nickname = nickname;
this.name = name;
this.passwd = passwd;
this.rpasswd = rpasswd;
this.tel = tel;
this.mail = mail;
this.Signed = signed;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMail() {
return mail;