Java 关闭程序后如何保存对象变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20924970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save object variables after closing my program?
提问by user3133300
I'm trying to learn Java and OOP by creating a monopoly banker program. However, I would like some object variables to be saved after I exit the program, so that after playing half of a monopoly game I can exit my program and then restart it with all the player balances saved.
我正在尝试通过创建垄断银行家程序来学习 Java 和 OOP。但是,我希望在退出程序后保存一些对象变量,以便在玩了一半的垄断游戏后,我可以退出我的程序,然后在保存所有玩家余额的情况下重新启动它。
I'm guessing this requires some sort of database?
我猜这需要某种数据库?
Here is a section of my code; I am trying to save the "balance" variable for all of my objects (players) after I exit my program.
这是我的代码的一部分;退出程序后,我试图为所有对象(玩家)保存“平衡”变量。
public class Monopoly {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//creates the users (name classes)
players player1 = new players();
players player2 = new players();
players player3 = new players();
players player4 = new players();
while (true) {
player1.balance=player1.finalbalance;
player2.balance=player2.finalbalance;
player3.balance=player3.finalbalance;
player4.balance=player4.finalbalance;
回答by Maurdekye
You have to save it to a file somewhere, the only surefire way to carry information between programs. You'll need to decide a format to save your file with. Look up some tutorials for reading/writing files, I'm sure it will help.
您必须将其保存到某个文件中,这是在程序之间传送信息的唯一可靠方法。您需要决定保存文件的格式。查找一些读/写文件的教程,我相信它会有所帮助。
回答by venergiac
Maybe I didn't really understant your question but if you need a method to catch the exit before the program exit (CTRL-C for instance) you van use an "exit hook", usefull also to free connection
也许我并没有真正理解您的问题,但是如果您需要一种方法来在程序退出之前捕获退出(例如 CTRL-C),您可以使用“退出挂钩”,这也有助于释放连接
see
看
回答by Evan Sharry
I would just serialize this object and deserialize it after you resume your game. I think it is the best way. Here you can find the way how to do that. http://www.tutorialspoint.com/java/java_serialization.htm
我只会序列化这个对象并在你恢复游戏后反序列化它。我认为这是最好的方法。在这里你可以找到如何做到这一点的方法。http://www.tutorialspoint.com/java/java_serialization.htm
回答by Philipp
While you could of course use a database, this would be quite overkill for a simple offline game. In that case it would be more common to save the game-state to a file (a "savegame").
虽然您当然可以使用数据库,但对于一个简单的离线游戏来说,这将是非常矫枉过正的。在这种情况下,将游戏状态保存到文件(“保存游戏”)会更常见。
By using the class ObjectOutputStream, you can write objects to a file. It converts the objects into a format which can then later be read with the class ObjectInputStream.
通过使用ObjectOutputStream类,您可以将对象写入文件。它将对象转换为一种格式,然后可以使用类ObjectInputStream读取该格式。