1

I have a class UserData that serializes objects,

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;
    }
}

To test this class , i wrote another class ,

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.");
            }
        }
    }
}

Output i am getting

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.

In the TestUserData class i am serializing 5 UserData objects, the serialization takes place well but during the de-serialization part , it is not able to deserialize past the first Object.

What should I change to make the program deserialize all the objects ??

cyberpirate92
  • 3,076
  • 4
  • 28
  • 46

1 Answers1

1

You cannot append to the serialization file like that. There are headers that are written, so in your file you will have <header><data><header><data><header><data>...

The file needs to be of the form <header><data><data><data><data>

So while your reading method is correct, your saving method is actually wrong. You need to write all the objects that go into the same file at the same time.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • But in my situation, i can't serialize all the objects at the same time, because the original purpose is using it in a application where users create their accounts at any time (i mean not at the same time) Any other alternatives other than serialization ?? – cyberpirate92 Jul 03 '13 at 10:16
  • With serialization, you would need to read the objects into memory, make required changes (such as add a user) then write them all back to the file. Another simple way would be to use a text file, with for example CSV format, having a single line for each user. A more robust solution would be to use a database (for example Java DB). – Kayaman Jul 03 '13 at 10:26
  • So i have to deserialize all the objects and then serialize them all again at the same time ? But wouldn't that increase the overhead ? – cyberpirate92 Jul 03 '13 at 10:31
  • 1
    Increase the overhead compared to what? You can't compare a working solution to a non-working solution. – user207421 Jul 04 '13 at 00:06