简体   繁体   中英

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.

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)? 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?

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. 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.

Is all of this correct?

Look into the Serializable library here . 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. Otherwise, you could look into google protocol buffers for a more densely packed data file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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