将java对象序列化为文本文件 [英] serialize java object to text file

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

问题描述

我有一个java库,我想将一个java对象的实例保存到一个文本文件中。我试图使用所有java库进行序列化和反序列化到xml: http://karussell.wordpress.com/2009/09/03/xml-serializers-for-java/ 但反序列化不起作用。我在这里发了一个问题: http://stackoverflow.com/questions/6139702/deserializing-xml-file-from-xstream 但似乎我无法得到一个解决方案。

I have a java library, I would like to save an instance of a java object to a text file. I have tried to use all java libraries for serialization and deserialization to xml: http://karussell.wordpress.com/2009/09/03/xml-serializers-for-java/ but deserializing does not work. I have posted a question here: http://stackoverflow.com/questions/6139702/deserializing-xml-file-from-xstream but It seems that I could not get a solution for that.

我也尝试序列化为 json 但是从json反序列化不起作用。

I also have tried to serialize to json but deserialize from json does not work.

所以,我想知道除了序列化为xml和json 之外,还有其他办法吗?从java对象序列化和反序列化(不能修改为将标签添加: @XmlRootElement(name =customer))到文本文件?

So, I would like to know apart of serializing to xml and json, is there any other way to do serialization and deserialization from a java object (cannot modify to add tags: @XmlRootElement(name="customer")) to text file?

提前致谢!

推荐答案

最简单的方法可能是使用本机Java序列化。它将生成对象的二进制表示,但您可以使用Base64对生成的字节数组进行编码,以将其转换为文本:

The easiest way is probably to use the native Java serialization. It will generate a binary representation of the object, but you can encode the generated byte array with Base64 to transform it to text:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(myObject);
oos.flush();
byte[] binary = baos.toByteArray();
String text = Base64.encodeBase64String(binary); // Base64 is in the apache commons codec library
// save text to a file

请注意,对象及其引用的每个对象(递归地)必须实现 java.io.Serializable 才能使其生效。

Note that the object, and every object it references (recursively) must implement java.io.Serializable for this to work.

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

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