Unable to a Custom Collection into a text File

72 Views Asked by At

I'm creating a generic type ArrayQueue and I'm trying to save an ArrayQueue into a text file.

My code:

public void saveToFile(ArrayQueueInterface<Payment> paymentQ){
    try {
        File file = new File("payment.dat");
        ObjectOutputStream ooStream = new ObjectOutputStream(new FileOutputStream(file));
        ooStream.writeObject(paymentQ);
        ooStream.close();
        //this.dispose();
      } catch (FileNotFoundException ex) {
        System.out.println("ERROR : File not found");
      } catch (IOException ex) {
        System.out.println("ERROR : Cannot save to file");
      }
}

The output showed was: "ERROR: Cannot save to file"

Does anyone have any idea how to fix this?

Here's the full stack trace :

at client.TestPayment.main(TestPayment.java:844)
java.io.NotSerializableException: adt.ArrayQueue
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at entity.PaymentOperation.saveToFile(PaymentOperation.java:337)
at entity.PaymentOperation.addPayment(PaymentOperation.java:72)
at client.TestPayment.init(TestPayment.java:545)
at client.TestPayment.main(TestPayment.java:844)
java.io.NotSerializableException: adt.ArrayQueue
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) 
1

There are 1 best solutions below

0
Alexander Ivanchenko On

In order to serialize ArrayQueueInterface<Payment> successfully, the implementation of your ArrayQueueInterface should implement Serializable interface (judging by the information in the stack-trace, it's not the case).

The same applies to the Payment class.

Note:

  • The whole object graph should be serializable, i.e. all the fields of Payment (and if some of the fields are custom type, then their field as well) should implement Serializable.

  • All primitive type are serializable, and all the standard classes from the JDK (apart from Object and Optional). So you need to care primary about your custom classes.

There's caveat regarding desirialization:

  • All the parent classes of your custom types should be either serializable, or provide a no-args constructor (explicit or implicit), because in order to create an instance of a subclass firstly we need to create an instance of the parent type. If this requirement is violated, your object would be serialized successfully, but attemp of desirialization would fail.