3

クラスのオブジェクトをファイルに保存し、その後、このファイルからオブジェクトをロードできるようにしたいと考えています。しかし、どこかで私は間違いを犯しており、どこにあるのかわかりません。助けてもらえますか?

public class GameManagerSystem implements GameManager, Serializable {

    private static final long serialVersionUID = -5966618586666474164L;
    HashMap<Game, GameStatus> games;
    HashMap<Ticket, ArrayList<Object>> baggage;
    HashSet<Ticket> bookedTickets;
    Place place;


    public GameManagerSystem(Place place) {
        super();

        this.games = new HashMap<Game, GameStatus>();
        this.baggage = new HashMap<Ticket, ArrayList<Object>>();
        this.bookedTickets = new HashSet<Ticket>();
        this.place = place;
    }
    public static GameManager createManagerSystem(Game at) {
        return new GameManagerSystem(at);
    }

    public boolean store(File f) {
        try {
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(games);
            oos.writeObject(bookedTickets);
            oos.writeObject(baggage);
            oos.close();
            fos.close();
        } catch (IOException ex) {
            return false;
        }
        return true;
    }
    public boolean load(File f) {
        try {
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fis);
            this.games = (HashMap<Game,GameStatus>)ois.readObject();
            this.bookedTickets = (HashSet<Ticket>)ois.readObject();
                this.baggage = (HashMap<Ticket,ArrayList<Object>>)ois.readObject();
            ois.close();
            fis.close();
        } catch (IOException e) {
            return false;
        } catch (ClassNotFoundException e) {
            return false;
        }
        return true;
    }
.
.
.
}


public class JUnitDemo {

    GameManager manager;

    @Before
    public void setUp() {
        manager = GameManagerSystem.createManagerSystem(Place.ENG);
    }

    @Test
    public void testStore() {
        Game g = new Game(new Date(), Teams.LIONS, Teams.SHARKS);
        manager.registerGame(g);
        File file = new File("file.ser");
        assertTrue(airport.store(file));
    }
}
4

3 に答える 3

5

この問題の解決策は、たとえば class などの他のオブジェクトを使用してA、オブジェクトHashMapをシリアル化したい場合、次のようにクラスのインターフェースを作成することです。HashMapimplementSerializableA

class A implements Serializable {
}

...
    HashMap<Integer,A> hmap;
...

そうしないと、そのオブジェクトはシリアライズできません。

私はそれが今この問題を解決することを願っています。

于 2010-05-02T11:34:53.077 に答える
0

閉じる前に oos.flush() を試してください。

于 2010-04-30T14:00:02.917 に答える
0

シリアル化中はオブジェクト グラフ全体が保持されることに注意してください。たとえば、GUI クラスへの参照がいくつかある場合は、それらもシリアライズ可能にするか、「一時的」としてタグ付けする必要があるため、Java はそれらをシリアライズしません。

于 2010-05-04T19:01:03.447 に答える