使用Java在文件中加载/存储对象

时间:2010-04-30 13:52:08

标签: java file load store

我想在文件中存储我的类中的对象,然后才能从该文件加载对象。但在某个地方,我犯了一个错误,无法弄清楚在哪里。我可以得到一些帮助吗?

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

3 个答案:

答案 0 :(得分:5)

这个问题的解决方案是当你使用其他对象时,让我们说类A,进入像HashMap这样的集合,并希望序列化HashMap对象,然后{{ 1}}类implement的接口Serializable,如下所示:

A

否则该对象将不可序列化。

我希望它现在能解决这个问题。

答案 1 :(得分:0)

关闭之前请尝试使用oos.flush()。

答案 2 :(得分:0)

请注意,序列化期间会保留整个对象图。例如,如果你有一些GUI类的引用,你或者必须使它们可序列化,或者将它们标记为“瞬态”,因此Java不会将它们序列化。