If statement with serialization

时间:2015-09-01 21:46:43

标签: java serialization deserialization

I can write to a file with values of my objects, but I want something like this: If (option1) serialise this object, else if option 2, serialise some other object, and so on.

My code works, but it's not obvious how to me, how I can have options to serialise and then de-serialise multiple objects. In short, consider a menu, if option selected, serialise that, or likewise for option 2, 3 etc.

Snippets of my working code are as follows, I am using Netbeans and running it via dos. This is a simple football game menu, trying to save and load a team name etc.

public class SerializeDemo
{
   public void Serialize()
   {


      ClubInfo club = new ClubInfo();
     club.teamName = "Arsenal";
     club.stadium = "Emirates";
     club.division = "Premier League";
      club.SSN = 11122333;
      club.stadiumCapacity = 60000;

      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("C:/tmp/club.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(club);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in C:/tmp/club.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }


   }
} // end class SerializeDemo

I can then de-serialise it, by selecting my "load game" option, and it successfully reads from the file and displays the objects data. Here is the de-serialise code.

import java.io.*;
public class DeserializeDemo
{
   public void Deserialize()
   {
      ClubInfo club = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("C:/tmp/club.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         club = (ClubInfo) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Club class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Saved game loaded...");
      System.out.println("Name: " + club.teamName);
      System.out.println("Stadium: " + club.stadium);
      System.out.println("Division: " + club.division);
     // System.out.println("SSN: " + club.SSN);
      System.out.println("Stadium Capacity: " + club.stadiumCapacity);
    }
}

How can I serialise more than one object? I thought about using an array of objects, but then I have problems with string states belonging to the objects.

0 个答案:

没有答案