开发者

How can I save an object in the file?

How can I save an object in the file? I have an Object obj,how can I save all its information such as:

m.getName();
m.getFamily() 

and t开发者_如何学Pythonhe others in the file???


Using an ObjectOutputStream you can write the object directly into the file.

 ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("filename.dat")));
 out.writeObject(obj);
 out.close();

This writes the Object obj out to the file. It can be read back in use an ObjectInputStream().


since xml is more readable and transferable, i use Simple Framework, or as mentioned you could do simple serialization.


You may be after serialization.


My workplace uses XStream, if ObjectOutputStream doesn't do the job.


If you just need to store the object and retrieve it back as a whole , better go with serialization.

In case, you want a readable file with the contents of the object , use file-IO API to write the contents to a file.


Yet another answer, but Apache Commons Lang has SerializationUtils

SerializationUtils.serialize(Serializable obj, OutputStream outputStream).


You can use Xstream to write objects to xml files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜