始终显示NotSerializableException异常(Java) - 序列化将不起作用

时间:2012-01-01 11:40:22

标签: java exception

给出以下代码:

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

      }
}

当我到达out.writeObject(view);行时,出现NotSerializableException .View对象包含一些其他对象,我从该代码中的文件中读取输入。假设正在创建View对象,这可能是什么问题?

View class : 

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


         /* Constructor */


        private Controller controller;

        public View() 

        {
            controller = new Controller();
        }

            ... ... 
            // more code 

    }

确切的信息是:

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)

这里有什么问题?

的问候,罗恩

2 个答案:

答案 0 :(得分:1)

Controller是否实施Serializable? <{1}}和View的所有字段都必须声明它们是可序列化的。

答案 1 :(得分:1)

异常消息非常明确:core.Controller类不可序列化。如果不能序列化,请将其设为Serializable,或将其声明为transient