user2920627
user2920627

Reputation: 95

Generic object Deserialization and Serialization java

Hello I am learning Generics and I having trouble deserializing an object(s) back from a file into a generic list and then printing.

result is an empty screen, even though i know that a dat file was created

I've tried a variety of ways.

My utilizes frames with ActionListener..

This is the ActionListener

 private class AddButtonActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // variables    
        String inputfName;
        String inputlName;
        String idInput;
        //String studentID;

        // capture input
        inputfName = sFirstName.getText();
        inputlName = sLastName.getText();
        idInput = sID.getText();

        //hold Student data


        //convert to Int
        //studentID = Integer.parseInt(idInput);

        //Create file
        StudentAddProcess sFile = new StudentAddProcess();
        sFile.writesFile(inputfName, inputlName, idInput );

    }

This these process the input

public class StudentAddProcess implements Serializable{

    String inputFirstName ;
    String inputLastName;
     String  inputID;


private Component Frame;

// Create File 
public void  writesFile ( String fName, String  lName, String Id ){

    // create T fields for student

     inputFirstName = fName;
     inputLastName = lName;
     inputID = Id;


try {


    ObjectOutputStream objectInputFile = new ObjectOutputStream(outStream);

    //Linkeked List of Student Objects
    GenericLinkedList<Student> studentList = new GenericLinkedList<>();

    // add Student Object to student 
    studentList.add(new Student(inputID, inputFirstName, inputLastName));

    //Where am i
    JOptionPane.showMessageDialog(Frame, "writing ...");

    //  for loop cycle and write student to fill

        for (int i =0 ;  i < studentList.size();i++) {
            objectInputFile.writeObject(studentList.get(i));
        }

       JOptionPane.showMessageDialog(Frame, "Complete :");
       //close file 
       objectInputFile.close();

Now we view the added object

    public class StudentViewFile implements Serializable {

    //variables 
    private String studentID; // holds passed user request to view
    private Component Frame;

    public void readFile(String  sID) throws IOException {

    studentID = sID;  // take passed variable
    //int studentID2 =Integer.getInteger(sID);

    try {
        //open read file 


        FileInputStream inStream = new         FileInputStream("StudentObjects.dat");// Stream of Objects

        ObjectInputStream objectInputFile = new ObjectInputStream(inStream);

       GenericLinkedList <Student> readRecord = new  GenericLinkedList<>();

         readRecord.add(new Student(studentID));

        for (int i = 0; i < readRecord.size(); i++) {
            readRecord = (GenericLinkedList) objectInputFile.readObject();

            // Diplay  records 
            System.out.println("File Objects" + readRecord.get(i) + " \n   next positions");

             // was going to try to print my test here  

            System.out.println(readRecord.toString());
        }

        // Read the serialized objects from the file.
        while (true) {

           readRecord = (GenericLinkedList) objectInputFile.readObject();



            // Display  records 
            System.out.println( "File Objects" + readRecord+ " \n next positions");

            //close file 
           objectInputFile.close();
          }

       } catch (EOFException e) {
        System.out.print("\n Exception caught ");

Any ideas would be great . Thank you in advance for your time and knowledge

Upvotes: 1

Views: 1653

Answers (3)

Stephen C
Stephen C

Reputation: 718758

Compare the way that you are writing the objects with the way that you are attempting to read them.

    for (int i =0 ;  i < studentList.size();i++) {
        objectInputFile.writeObject(studentList.get(i));
    }

This writes a sequence of Student objects.

    readRecord = (GenericLinkedList) objectInputFile.readObject();

This attempts to read something and cast it to GenericLinkedList. But it won't be one of those. It will actually be a Student, so you will get an exception.

The other problem is this:

    GenericLinkedList <Student> readRecord = new  GenericLinkedList<>();
    readRecord.add(new Student(studentID));
    for (int i = 0; i < readRecord.size(); i++) {
        readRecord = (GenericLinkedList) objectInputFile.readObject();

How many times do you really want to go round the loop? Where is that number actually coming from?

There are a number of ways to deal with this; for example:

  1. Write (and then read) the entire list as a single object
  2. Start the stream by writing the list size (studentList.size()) as an int. When reading, first read the list size, and then read that number of Student objects.
  3. Read using a while (true) loop and catch / handle the EOFException.

(I note that you have attempted to do alternative 3 ... following the broken code. Of course that won't get past your broken code, so that won't work. What are you thinking?)

Upvotes: 1

Simon L
Simon L

Reputation: 173

When you serialized the list to file, you serialized each student object in the list through a loop.

    for (int i =0 ;  i < studentList.size();i++) {
        objectInputFile.writeObject(studentList.get(i));
    }

So when you deserialized it, and you should deserialize the students one by one, rather than the whole list

    GenericLinkedList <Student> readRecord = new  GenericLinkedList<>();
    Student student;
    while (true) {
        student = (Student) objectInputFile.readObject();
        // Display  records 
        System.out.println( "File Objects" + student + " \n next positions");
        readRecord.add(student);
    } catch (EOFException e) {
        System.out.print("\n Exception caught ");
        //close file 
        objectInputFile.close();
    }

Upvotes: 0

Vadim Fedorenko
Vadim Fedorenko

Reputation: 2561

Hm, look at this code below:

import java.io.*;
import java.util.LinkedList;

public class Main {

    private static class GenericLinkedList<T> extends LinkedList<T> {

    }

    private static class Student implements Serializable {

        final String name;

        public Student(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

    }

    public static void main(String[] args) throws IOException {

        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {

                GenericLinkedList<Student> students = new GenericLinkedList<>();

                seed(students);

                objectOutputStream.writeObject(students);

                try(ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) {

                    Object readObject = objectInputStream.readObject();

                    GenericLinkedList<Student> readStudents = (GenericLinkedList<Student>) readObject;

                    for (Student student : readStudents) {
                        System.out.println(student.getName());
                    }

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void seed(GenericLinkedList<Student> students) {
        for (int i = 0; i < 5; i++) {
            students.add(new Student("test #" + i));
        }
    }

}

It normally works with generic list. Try this code by yourself

Upvotes: 0

Related Questions