gpt4 book ai didi

java - 在 Java 文件中加载/存储对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:58:27 26 4
gpt4 key购买 nike

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

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

最佳答案

这个问题的解决方案是,当你使用其他对象时,比如类 A,到一个像 HashMap 这样的集合中,并且想要序列化 ​​HashMap 对象,然后实现A 的接口(interface)Serializable,如下所示:

class A implements Serializable {
}

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

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

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

关于java - 在 Java 文件中加载/存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2744962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com