Java序列化与纯文本文件 [英] Java Serialization vs Plain text file

查看:117
本文介绍了Java序列化与纯文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.假设我有一个游戏,其中包含一些瓷砖和玩家.所有这些对象都需要保存,以便以后可以开始游戏并恢复状态.我已经使用XML文件或纯文本文件之类的简单文件来执行此操作,在这里我只是将磁贴类型和坐标打印到文件中,然后进行读取,然后根据文本文件中的信息进行解析和创建新对象.

我的问题是,当我仅可以将对象的属性保存到文本文件时,为什么要序列化它们?许多游戏会因使用文本文件而序列化其​​对象吗?有什么好处吗?我可以想象序列化可以保存对象的实例,这样您以后就不必再创建对象的新实例了,就像必须使用文本文件一样.但是我真的不知道!

解决方案

在Java中进行序列化的主要好处是,您不必像现在那样手动将文件读/写.您只需要实现 Serializable 接口和java会照顾它.

这是一个在Java中使用序列化的不错的教程: http://www.tutorialspoint.com/java/java_serialization.htm

I'm sort of confused. Let's say I have a game that consists of some tiles and players. All these objects need to be saved so I can later start the game and restore the state. I already do this with simple files like an XML file or plain text files, where I just print the tile type and coordinates into the file and then later read, and parse and create new objects based on the information in the text file.

My question is why should I serialize my objects when I can just save their attributes to a text file? Do many games serialize their objects instea of using text files? Is there any benefit? I could imagine that serializing saves an instance of the object so that you don't have to later create a new instance of the object, like you would have to with a text file. But I really dont know!

解决方案

The main benefit of serialization in java is that you don't have to manually do the reading/writting into files, as you are doing now. You just need to implement the Serializable interface and java takes care of it.

Here's a nice tutorial of using serialization in Java: http://www.tutorialspoint.com/java/java_serialization.htm

这篇关于Java序列化与纯文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆