简体   繁体   中英

Object Serialization and Deserialization using ArrayList in Java

I am trying to serialize an object array and write it to a file named address.ser and then read back from the file, deserialize the object array and display its attributes. I tried serializing the whole arrayList at once(deserializing it in a single session while reading) and also tried serializing each object of the object array one by one(deserializing it one by one while reading). The problem is, while reading back from the address.ser file I am getting data only of the last object which was written and none other.

Here is the code snippet:

Employee[] a=new Employee[5];

    List<Employee> arr=new ArrayList<Employee>();

    for(int i=0;i<=4;i++)
    {
    a[i]=new Employee();
    System.out.println("Enter name,age,height,weight,house_no:");
    a[i].name=sc.next();
    a[i].age=sc.nextInt();
    a[i].height=sc.nextDouble();
    a[i].weight=sc.nextDouble();
    a[i].house_no=sc.nextInt();
    arr.add(a[i]);
    }

This is the code snippet for writing objects to address.ser:

for(int i=0;i<=4;i++)
    {
    try
    {
    fout = new FileOutputStream("e:\\address.ser");
    oos = new ObjectOutputStream(fout);   
    oos.writeObject(a[i]);
    //oos.writeChars("\n");
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
    oos.close();
    fout.close();
    }
    }

This is the code snippet for reading objects from address.ser:

List<Employee> recordList=new ArrayList<Employee>();
    for(int i=0;i<=4;i++)
    {
    try
    {
        file = new FileInputStream("e:\\address.ser");
        input = new ObjectInputStream (file);

        //deserialize the List
        Employee readCase=(Employee) input.readObject();
        recordList.add(readCase);
        System.out.print("Employee "+i+" ");
        System.out.print((recordList.get(i).name)+" ");
        System.out.print((recordList.get(i).age)+" ");
        System.out.print((recordList.get(i).height)+" ");
        System.out.print((recordList.get(i).weight)+" ");
        System.out.print((recordList.get(i).house_no)+" ");
        System.out.println();

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
    file.close();
    input.close();
    }
    }

The final output being:

输出图像

This is the way to do,

public class Test {
    public static void main(String[] args) {
Employee employee=new Employee("jhon");
Employee employee2=new Employee("jojo");
Employee employee3=new Employee("albin");
ArrayList<Employee> list=new ArrayList<Employee>();
list.add(employee);
list.add(employee2);
list.add(employee3);

try {
    FileOutputStream outputStream=new FileOutputStream("add.ser");
    ObjectOutputStream objectOutputStream= new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(list);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


try {
    FileInputStream inputStream=new FileInputStream("add.ser");
    ObjectInputStream objectInputStream =new ObjectInputStream(inputStream);
    ArrayList<Employee> list2=(ArrayList<Employee>) objectInputStream.readObject();
    for (Employee employee4 : list2) {
        System.out.println(employee4.getName());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
    }
}

Corrected Solution

You're overwriting the file for each element you attempt to serialize. Therefore, the last serialized element remains. A file of serialized data has a header, so you must write your data in one shot.

fout = new FileOutputStream("e:\\address.ser");
oos = new ObjectOutputStream(fout);   
for(int i=0;i<=4;i++)
{
     try
     {
        oos.writeObject(a[i]);
     }catch(Exception e){}
}

However , it's more efficient to serialize the entire list in one shot.

The problem is you are trying to write the object in a wrong way. You are writing each element of the ArrayList in a same file. So what is happening is a new element is replacing the old one. So write the whole List at a time liek

oos.writeObject(yourList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM