反序列化对象时StreamCorruptedException

时间:2013-07-03 10:08:31

标签: java file serialization deserialization

我有一个用于序列化对象的类UserData,

import java.io.*;

public final class UserData implements Serializable
{
    private String name,username,password;
    private boolean male;
    private int age;

    public void setName(String name) { this.name = new String(name); }
    public void setUsername(String username) {this.username = new String(username); }
    public void setPassword(String password) {this.password = new String(password); }
    public void setAge(int age) { this.age = age; }
    public void setGender(boolean gender) { this.male = gender; }

    public String getName() { return new String(this.name); }
    public String getUsername() { return new String(this.username); }
    public String getPassword() { return new String(this.password); }
    public int getAge() { return this.age; }
    public boolean getGender() { return male; }

    public static void writeUserDataToFile(UserData data,String fileName)
    {
        try
        {
            if(data == null)
            {
                return;
            }
            ObjectOutputStream objOutput = new ObjectOutputStream(new FileOutputStream(new File(fileName),true));
            objOutput.writeObject(data);
            objOutput.flush();
            objOutput.close();
        }
        catch(FileNotFoundException ex)
        {
            System.out.println("Error : Cannot Save Data , The given filename \""+fileName+"\" is not valid.");
            return;
        }
        catch(NotSerializableException ex)
        {
            System.out.println("Error : It has been found that some data is not Serializable!");
            return;
        }
        catch(IOException ex)
        {
            System.out.println("Error : IOException has been encountered,");
            return;
        }
        catch(SecurityException S)
        {
            System.out.println("Error : Security Exception has been Encountered.");
            return;
        }
        catch(Exception e)
        {
            System.out.println("Error : Unknown Exception thrown!");
            return;
        }
        System.out.println("Sucess : Data written to \""+fileName+"\".");
    }
    public static UserData checkCredentials(String fileName,String userName,String passWord)
    {
        try
        {
            ObjectInputStream objInput = new ObjectInputStream(new FileInputStream(new File(fileName)));
            UserData data;
            while((data = (UserData)objInput.readObject())!=null)
            {
                if( userName.equals(data.getUsername()) && passWord.equals(data.getPassword()) )
                    return data;
            }
            objInput.close();
        }
        catch(Exception ex)
        {
            System.out.println("Error : Unknown Exception Caught while deserializing object.");
            ex.printStackTrace();
        }
        return null;
    }
}

为了测试这个课,我写了另一个课,

public class TestUserData
{
    public static void main(String args[])
    {
        UserData data = new UserData();
        System.out.println("Serializing objects .... ");
        for(int i=0;i<5;i++)
        {
            data.setName("John");
            data.setAge(10+i);
            data.setGender((i%2==0)?true:false);
            data.setUsername("John"+i);
            data.setPassword(i+"John");
            UserData.writeUserDataToFile(data,"testSerial.dat");
        }
        System.out.println("de-Serializing objects .... ");
        for(int i=0;i<5;i++)
        {
            data = UserData.checkCredentials("testSerial.dat","John"+i,i+"John");
            if(data!=null)
            {
                System.out.println("Name : "+data.getName());
                System.out.println("Age  : "+data.getAge());
                System.out.println("Gender : "+(data.getGender() ? "Male" : "Female"));
            }
            else
            {
                System.out.println("Data for Object "+i+" not de-serialized.");
            }
        }
    }
}

输出我

Serializing objects .... 
Sucess : Data written to "testSerial.dat".
Sucess : Data written to "testSerial.dat".
Sucess : Data written to "testSerial.dat".
Sucess : Data written to "testSerial.dat".
Sucess : Data written to "testSerial.dat".
de-Serializing objects .... 
Name : John
Age  : 10
Gender : Male
Error : Unknown Exception Caught while deserializing object.
java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at UserData.checkCredentials(UserData.java:67)
    at TestUserData.main(TestUserData.java:19)
Data for Object 1 not de-serialized.
Error : Unknown Exception Caught while deserializing object.
java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at UserData.checkCredentials(UserData.java:67)
    at TestUserData.main(TestUserData.java:19)
Data for Object 2 not de-serialized.
Error : Unknown Exception Caught while deserializing object.
java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at UserData.checkCredentials(UserData.java:67)
    at TestUserData.main(TestUserData.java:19)
Data for Object 3 not de-serialized.
Error : Unknown Exception Caught while deserializing object.
java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at UserData.checkCredentials(UserData.java:67)
    at TestUserData.main(TestUserData.java:19)
Data for Object 4 not de-serialized.

在TestUserData类中,我正在序列化5个UserData对象,序列化很好,但在反序列化部分,它无法反序列化超过第一个Object。

我应该更改什么才能使程序反序列化所有对象?

1 个答案:

答案 0 :(得分:1)

您不能像这样附加到序列化文件。有标题已写入,因此在您的文件中,您将有<header><data><header><data><header><data>...

该文件必须采用<header><data><data><data><data>

的格式

因此,当您的阅读方法正确时,您的保存方法实际上是错误的。您需要同时写入同一文件中的所有对象。