JAN
JAN

Reputation: 21885

NotSerializableException exception always appears (Java) - Serialization won't work

Given the following code :

import java.io.*;

public class Main {


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

         View view = null;

          try
          {
              /* Open the file that is the first command line parameter
                 text file must be inside the project library , not in the src library */

              FileInputStream fstream = new FileInputStream("input.txt");                             
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader groupsFile = new BufferedReader(new InputStreamReader(in));            

              view = new View();
              view.insertTeamsFromFile(groupsFile);
              view.startCompetition();                
              in.close();
          }  

          //Catch exception if any
          catch (Exception e)    {    System.err.println("Error: " + e.getMessage());     }


        try 
        {

            String filename = "view.txt";
            FileOutputStream fos = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(view);
            out.close();
            System.out.println("Object Persisted");
        } 

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

      }
}

When I get to the line out.writeObject(view); the NotSerializableException appears.The View object includes a few other objects , and I read input from a file within that code . Assume that the View object is being created just fine , what might be the problem here ?

View class : 

    public class View implements Serializable {
import java.io.*;
import java.util.*;


         /* Constructor */


        private Controller controller;

        public View() 

        {
            controller = new Controller();
        }

            ... ... 
            // more code 

    }

The exact message is :

java.io.NotSerializableException: core.Controller
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
    at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)

What's wrong here ?

Regards,Ron

Upvotes: 0

Views: 1254

Answers (2)

JB Nizet
JB Nizet

Reputation: 692121

The exception message is quite clear: the core.Controller class is not serializable. Make it implement Serializable, or declare it as transient if it must not be serialized.

Upvotes: 2

rsp
rsp

Reputation: 23373

Does Controller implement Serializable? All field of View and Controller must declare that they are serializable.

Upvotes: 1

Related Questions