开发者

Can objects be written to and read from files?

I think the answer is yes, but I just wanted to make sure.

anyone's help would be gr开发者_Go百科eatly appreciated


Yes, it's called serialization. It typically involves creating a String representation of the class's data, and then creating a method which can parse the saved data to recreate an equivalent Object. The code for saving and restoring can either be part of the Object's Class or provided elsewhere in a larger framework.


An object itself can't really be stored to a file. If you want, you can serialize the data in the object to some kind of document, such as an XML file. You can define how the data is stored in it. Then when you want to read it, you just need to open and parse the XML document back into your object, the opposite from how you saved it.

http://java.sys-con.com/node/37550


Serialization is the process of converting an object state to a sequence of bytes. These bytes can be then stored on the disk as a file or sent across the sockets or stored in a DB as BLOB etc. The inverse process is called De-serialization.

Not all objects can be serialized though. Only the ones that implement Serializable interface. Read here for more details.

There are various serialization types like binary serialization (compact, faster etc), textual serialization (slower, might take more space but human readable).

Java's serialization format is not portable and some problems. There are better alternatives to Java's native serialization. Based on your requirement you can choose the best one. Here are few protobuf, thrift, json, xml, YAML


Beyond default JDK serialization that is already mentioned, and XML serialization (using either suggested XStream, or faster JAXB) (which is included in JDK 6, see package 'javax.xml.bind'), there are many other options.

For example JSON serialization using Jackson is very efficient and also bit more compact and readable (latter is subjective of course) than XML serialization.


java serialization


Absolutely! Like others pointed out, it's called serialization. Give a look at the XStream library. I think it's great for serializing to XML. It helped me a lot in my projects, and it's very, very easy to use.


To use default serialization the classes must implement Serializable interface

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜