I am getting an error ( IOException ) when I try to write to a serializable file. The object to be saved in turn contains an object both of which are serializable. The following stack trace error is being printed:
java.io.NotSerializableException: GameObject at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at SerializeGame.saveGame(SerializeGame.java:26) at TicTacToeFinal.saveGame(TicTacToeFinal.java:379) at TicTacToeFinal.playGame(TicTacToeFinal.java:174) at TicTacToeFinal.newGame(TicTacToeFinal.java:88) at TicTacToeFinal.menu(TicTacToeFinal.java:34) at TicTacToeFinal.loadGame(TicTacToeFinal.java:343) at TicTacToeFinal.menu(TicTacToeFinal.java:35) at TicTacToeFinal.mainScreen(TicTacToeFinal.java:19) at TicTacToeFinalTest.main(TicTacToeFinalTest.java:14)
Here is the GameObject class:
import java.io.*; public class GameObject implements Serializable{ TicTacToeAlgorithm game; int startWith; int cChances; int uChances; GameObject(TicTacToeAlgorithm game, int startWith, int cChances, int uChances) { this.game=game; this.startWith=startWith; this.cChances=cChances; this.uChances=uChances; } }
And following is the TicTacToeAlgorithm class:
import java.util.Random; import java.util.Arrays; import java.io.*; public class TicTacToeAlgorithm implements Serializable{ int[][] grid; int difficultyLevel; public TicTacToeAlgorithm(int difficultyLevel) { grid=new int[9][9]; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) grid[i][j]=0; } this.difficultyLevel=difficultyLevel; // 1 easy 2 difficult //................................... contains any methods }
Following is the code that I have used to serialise the file:
import java.io.*; public class SerializeGame { ObjectOutputStream output; public void openFile(){ try{ output = new ObjectOutputStream(new FileOutputStream( "savedGame.ser" ) ); } catch(Exception e) { System.out.println("Error creating game file"); } } public void saveGame(GameObject gameObject) { openFile(); try{ output.writeObject(gameObject); System.out.println("\nGame saved"); } catch(IOException e) { System.out.println("Error saving game file: IOException"); e.printStackTrace(); } closeFile(); } public void closeFile() { try{ if(output!=null) output.close(); } catch(Exception e) { System.out.println("Error closing game file"); } } }
I am in very much need of it. Any help would be appreciated.