简体   繁体   English

使用FileOutputStream将数据结构写入文件吗?

[英]Writing Data Structures to files using FileOutputStream?

I have an android application and want to store/retrieve to memory a data structure that I created on the onPause()/onResume() methods so that the data will persist between runs via FileOutputStream/FileInputStream, which is the standard practice for this. 我有一个android应用程序,想要存储/检索在onPause()/ onResume()方法上创建的数据结构,以便数据在FileOutputStream / FileInputStream的运行之间持久存在,这是此操作的标准做法。

So, how do I save a data structure to a file so that I can obtain it later (I've seen examples of doing it with Strings but not other objects)? 因此,如何将数据结构保存到文件中以便以后获得(我已经看到了使用String而不是其他对象的示例)? Am I forced to create a getBytes() function for my data structure and the subsequent objects which it contains in addition to making constructors for all of these objects that creates them from byte arrays? 除了为从字节数组创建它们的所有这些对象构造函数之外,我是否被迫为我的数据结构及其包含的后续对象创建getBytes()函数?

Edit: Ah, okay; 编辑:啊,好吧; so this is called serialization. 所以这叫做序列化。 Is the the following correct? 以下正确吗?

To write: 来写:

FileOutputStream fileOut = new FileOutputStream("filename");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();

To read: 读书:

FileInputStream fileIn = new FileInputStream("filename");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (ObjectType) in.readObject();
in.close();
fileIn.close();

Edit2: Also, the data structure and contained objects (and sub-objects) should all implement Serializable. Edit2:此外,数据结构和包含的对象(和子对象)都应实现Serializable。 So for instance, if I had a BST of ArrayLists of Dogs then I would make the BST, ArrayList, and Dog classes all implement Serializable and then call the functions above. 因此,例如,如果我有一个Dogs的ArrayLists的BST,那么我将使BST,ArrayList和Dog的类全部实现Serializable,然后调用上面的函数。

Is all of this correct? 所有这些正确吗?

Look into the Serializable library here . 在这里查看Serializable库。 This allows you to write a class directly down to a non-human readable file, then can be read back in the same way. 这使您可以直接将类写到一个非人类可读的文件中,然后可以用相同的方式将其读回。

Its common to serialize your data with JSON or XML. 使用JSON或XML序列化数据是常见的做法。 Otherwise, you could look into google protocol buffers for a more densely packed data file. 否则,您可以查看Google协议缓冲区以获取更密集的数据文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM