473,395 Members | 2,192 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Load saved game from file using ObjectInputStream

42
I'm trying to figure a good way to handle saving game state to file (common save/load game function in games). ObjectOutput/InputStream seems most promising so far.

However,the object I'm saving contains lots of other objects which in turn contain other objects. All objects implement Serializable (I've given them all serialVersionUID = 1, not sure whether it matters).

It seems to write the object properly but loading it is a bit of a problem.

This is the function I'm using:

Expand|Select|Wrap|Line Numbers
  1. private Game readObject(String n)throws IOException, ClassNotFoundException{
  2.         ObjectInputStream ois = null;
  3.         Game ga = null; 
  4.         //Construct the ObjectInputStream object
  5.         ois = new ObjectInputStream(new FileInputStream("res/"+n+".gla"));/
  6.  
  7.         Object obj = ois.readObject(); //this should somehow be made to read the entire file? 
  8.         if (obj instanceof Game) { //obviosly this is not enough. Returns always null.
  9.  
  10.             ga = (Game)obj;
  11.         }
  12.         if (ois != null) {
  13.             ois.close();
  14.         }
  15.         return ga;
  16.     }
Object's class variables:

Expand|Select|Wrap|Line Numbers
  1. private final static long serialVersionUID = 1;
  2. private Tavern tavern;
  3. private Blacksmith blacksmith;
  4. private Spellshop spellshop;
  5. private Vector<Team> teams;
  6. private Team activeTeam;
  7. private Gladiator currentGladiator = null;
  8. private Season season;
  9. private Battle battle;
  10. private int currentseason;
  11. private int humanplayers = 0;
Any help or insight upon the matter would be greatly appreciated.
Jun 26 '09 #1
10 4626
JosAH
11,448 Expert 8TB
@Humakt
Care to elaborate a bit on the 'bit of a problem'? Doesn't it read the object from the Stream? Make sure that all your member objects of a Game object are Serializable or make them transient.

btw, if you're using an IDE most likely it can generate a VersionID value for you.

kind regards,

Jos
Jun 26 '09 #2
Humakt
42
@JosAH
Well, I think the problem is that there are multiple objects in the file, but they are all (one way or other) part of this game object. I tried reading object in loop as well but it also returned null.

I correct the first post in sec.

This is the function I use to write the object:

Expand|Select|Wrap|Line Numbers
  1. private void writeObject(String file)throws IOException{
  2.         FileOutputStream fos = new FileOutputStream("res/"+file+".gla");
  3.         ObjectOutputStream oos = new ObjectOutputStream(fos);
  4.         oos.writeObject(this);
  5.         oos.close();
  6.     }
Jun 26 '09 #3
JosAH
11,448 Expert 8TB
@Humakt
For debugging make all your member objects transient and try again; you should be able to write/read an (almost) empty Game object. Next add the member objects again and give them another SerialVersionUID number and try again. Your code looks reasonable.

kind regards,

Jos
Jun 26 '09 #4
r035198x
13,262 8TB
You are telling us what you think is causing the problem not the actual results of your program.
Basically you must read what you have written. If you write a Jos, read back a Jos, not a JosAH, Loretta or any other such variants thereof.
Jun 26 '09 #5
Humakt
42
Sorry, was in a hurry earlier. Seems that ObjectInputStream does find the object in question (I tried printing values from object's objects) inside the loop.

However it seems it gets stuck in exception and the function doesn't have the chance to return the object.

These are the exceptions I'm testing in function:

Expand|Select|Wrap|Line Numbers
  1. public Game loadGame(String n){
  2.         Game ga = null;
  3.         try {
  4.             ga = this.readObject(n);
  5.         } catch (EOFException ex) { //This exception will be caught when EOF is reached
  6.         } catch (ClassNotFoundException ex) {
  7.             ex.printStackTrace();
  8.         } catch (FileNotFoundException ex) {
  9.             ex.printStackTrace();
  10.         } catch (IOException ex) {
  11.             ex.printStackTrace();
  12.         } 
  13.         if(ga==null)System.out.println("interesting...");
  14.         else System.out.println("Very interesting");
  15.         return ga;
  16.     }
New code for readObject:
Expand|Select|Wrap|Line Numbers
  1.  private Game readObject(String n)throws IOException, ClassNotFoundException{
  2.         ObjectInputStream ois = null;
  3.         Game ga = null; 
  4.         //Construct the ObjectInputStream object
  5.         ois = new ObjectInputStream(new FileInputStream("res/"+n+".gla"));
  6.         Object obj = null;
  7.         boolean found = false;
  8.         while((obj = ois.readObject())!= null&&!found){
  9.             if (obj instanceof Game) {
  10.  
  11.                 ga = (Game)obj;
  12.                 System.out.println(ga.getActiveTeamName()); //these two lines print what was excepted
  13.                 System.out.println(ga.getCurrentGladiator().getName());
  14.                 found = true;
  15.             }
  16.         }
  17.  
  18.         System.out.println(ga.getActiveTeamName()); //doesn't get here
  19.         if (ois != null) {
  20.             ois.close();
  21.         }
  22.         return ga;
  23.     }
I am using Swing and MVC model and also DAO (but none of them are part of the objects Game object knows).

EDIT: Ok. End of file exception seems to be the reason. Trying to fix it..
Jun 26 '09 #6
JosAH
11,448 Expert 8TB
@Humakt
Are you sure you're closing the ObjectOutputStream after writing and not the wrapped FileOutputStream? There might still be something in the buffer of the first stream that doesn't get written that way.

kind regards,

Jos
Jun 27 '09 #7
Humakt
42
Sorry, was on vacation. I am back now and problem still seems to persist.

@JosAH
Yes, I posted the function for it above. I am using Eclipse as an IDE.
Jul 14 '09 #8
JosAH
11,448 Expert 8TB
@Humakt
Make Eclipse generate those version IDs for the classes that are saved because they're part of your Game object (it's a 'quick fix' in Eclipse). You're logically writing one object so you read one object (there's no loop involved). Show us the Exception stack trace that is thrown.

kind regards,

Jos
Jul 15 '09 #9
Humakt
42
Seems that it is working now that I made Eclipse generate them (also made small adjustments). I'm bit curious though, will I always have to make Eclipse regenerate version ID's when I make adjustments to class implementing serializable?

Big thanks for the help.
Jul 15 '09 #10
JosAH
11,448 Expert 8TB
@Humakt
You're welcome of course; w.r.t. that ID: better do so because two different classes with a same ID number make no sense: i.e. they are loaded but the fields may not correspond. When everything is stable you don't need to change that ID number anymore. Also read the API documentation for the Serializable interface; it explains everything for that ID number.

kind regards,

Jos
Jul 15 '09 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: Bruce A. Julseth | last post by:
When I execute this SQL statement in my PHP code, I get an error "File '.\Address.txt' not found (Errcode: 2)" $File = addslashes(".\Address.txt"); $SQL = "Load Data InFile \"" . $File . "\"...
2
by: Murat Tasan | last post by:
i'd like to have a constructor that loads an object from disk and returns it... kinda like: class MyClass { MyClass(File f) { ObjectInputStream s = new ObjectInputStream(new...
1
by: maya2000 | last post by:
Hello, Below code has a problem to read a data. It seems the non-primitive data are the reason. How can I save this Map into a file, and read it later? Thanks in advance. ...
3
by: Vin | last post by:
Hi, I save the drwan stuff on a GLView using CsGL like this: Size s = Size; s.Width = 540; s.Height = 435; Bitmap b = new Bitmap(s.Width, s.Height, PixelFormat.Format32bppArgb); BitmapData...
3
by: ek03 | last post by:
I have a web application that saves/loads XML documents. On occasion, an error is logged on the call to XmlDocument.Load: "process cannot access the file <filepath here> because it is being used by...
10
by: lamxing | last post by:
Dear all, I've spent a long time to try to get the xmldocument.load method to handle UTF-8 characters, but no luck. Every time it loads a document contains european characters (such as the...
5
by: alesitaam | last post by:
Help!!!! Im new using python, currently writing a program which tests one game, IQ test. When the module is run, the program should ask user to choose the game to start. Also, I'm using Try...Except...
5
by: herenbdy | last post by:
I've been working on a Java based game in order to learn Java, but the game is functional only within my IDE (Eclipse). This image shows the file structure of my project:...
3
by: blackraven1425 | last post by:
The ObjectInputStream in this code is giving a EOFException. Do I need to do anything special to get this to work withou the EOF exception? It gives the exception at the line of the first instance of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.