在文件中写入和读取 arraylist 对象
我知道这很简单,但我没有互联网接入,而且这个网吧键盘很糟糕,所以如果有人可以回答这个问题。
课程是什么?只要朝正确的方向踢我一脚即可。有一个简单的 arraylist 对象,我想将其写入文件或从文件中读取。 谢谢
this is simple I know, but i don't have internet access and this netcafes keyboard sucks, so if someone can answer this question please.
what would be the class ? just give me a kick in the right direction. there is simple arraylist object that I want to write and read to/ from file.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个问题没有一个明确的答案。这取决于文件的格式和列表中的对象。你需要一个序列化器。例如,您可以使用 BinaryFormatter 将对象实例序列化为二进制文件,但您的对象必须是 可序列化。另一种选择是使用 XML 的 XmlSerializer格式。
更新:
这是 BinaryFormatter 的示例:
There's no single definitive answer to this question. It would depend on the format of the file and the objects in the list. You need a serializer. For example you could use BinaryFormatter which serializes an object instance into a binary file but your objects must be serializable. Another option is the XmlSerializer which uses XML format.
UPDATE:
Here's an example with BinaryFormatter:
由于您没有提到该数组包含什么类型的数据,我建议以二进制格式编写该文件。
这是一个关于如何读写的很好的教程二进制格式。
基本上,您需要使用
BinaryReader
和BinaryWriter
类。[编辑]
Since you did not mention what type of data this array contains, I would suggest writing the file in binary format.
Here is a good tutorial on how to read and write in binary format.
Basically, you need to use
BinaryReader
andBinaryWriter
classes.[Edited]
如果数组列表中的对象是可序列化的,则可以选择二进制序列化。但这意味着任何其他应用程序都需要知道序列化,然后才能使用该文件。您可能想澄清您使用序列化的意图。那么问题来了,为什么需要进行序列化呢?如果很简单,供您自己(此应用程序)使用,您可以考虑二进制序列化。确保您的对象是可序列化的。否则,您需要考虑 XML 序列化。
对于二进制序列化,您可以想到这样的代码:
If your objects in the arraylist are serializable, you can opt for binary serialization. But this means any other application need to know the serialization and then only can use this files. You may like to clarify your intent of using the serialization. So the question remains, why do you need to do a serialization? If it is simple, for you own (this application's) use, you can think of binary serialization. Be sure, your objects are serializable. Otherwise, you need to think of XML serialization.
For Binary serialization, you can think of some code like this: