简体   繁体   English

Android:我可以将Java对象写入文件并在以后检索吗?

[英]Android: Can I write a Java Object to a file and retrieve it later?

I use Spannables with EditTexts. 我将Spannables与EditTexts一起使用。

So I want to store a object of Spannable to a file (or whatever the storage media) and retrieve it later. 所以我想将一个Spannable对象存储到一个文件(或任何存储介质)中,然后再检索它。

(Don't reply with alternatives ways to store Spannable, I have tried most of them such as converting to html) (不要用其他方法来存储Spannable,我已经尝试了其中大多数方法,例如转换为html)

Is there a way to do this? 有没有办法做到这一点?

Yes, you can do with the use of Serialization. 是的,您可以使用序列化。 Read this page: 阅读页:

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. 序列化对象意味着将其状态转换为字节流,以便可以将字节流还原回该对象的副本。 A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable. 如果Java对象的类或其任何超类实现java.io.Serializable接口或其子接口java.io.Externalizable,则该对象是可序列化的。 Deserialization is the process of converting the serialized form of an object back into a copy of the object. 反序列化是将对象的序列化形式转换回该对象的副本的过程。

For example, the java.awt.Button class implements the Serializable interface, so you can serialize a java.awt.Button object and store that serialized state in a file. 例如,java.awt.Button类实现了Serializable接口,因此您可以序列化java.awt.Button对象并将该序列化状态存储在文件中。 Later, you can read back the serialized state and deserialize into a java.awt.Button object. 以后,您可以读回序列化状态并将其反序列化为java.awt.Button对象。

This page has an example also. 此页面也有一个示例。 How to serialize and de-serialize an object. 如何序列化和反序列化对象。

And if you need a full code sniplet you can follow this - 如果您需要完整的代码段,则可以按照以下步骤操作 -

I hpw this would help you. 我hpw这将帮助您。

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

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