Stephanie Dente
Stephanie Dente

Reputation: 71

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 greatly appreciated

Upvotes: 2

Views: 297

Answers (7)

rafalopez79
rafalopez79

Reputation: 2076

To use default serialization the classes must implement Serializable interface

Upvotes: 0

Brad Mace
Brad Mace

Reputation: 27886

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.

Upvotes: 9

Aravind Yarram
Aravind Yarram

Reputation: 80176

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

Upvotes: 2

StaxMan
StaxMan

Reputation: 116522

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.

Upvotes: 1

Joanis
Joanis

Reputation: 1679

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.

Upvotes: 0

user467871
user467871

Reputation:

java serialization

Upvotes: 0

zsalzbank
zsalzbank

Reputation: 9857

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

Upvotes: 2

Related Questions