Question on storing objects
i am trying to build an application that reads in a bunch of strings from
a file into an object. each set of 5 values becomes one object. I am confused
on the process of storing the object for retrieval later. basically I want
to be able to click through the objects one at a time and later dump them
back to a new file..
Anybody have an idea of where I start.. Thanks in advance
Re: Question on storing objects
"deaton" <firstname.lastname@example.org> wrote:
>i am trying to build an application that reads in a bunch of strings from
>a file into an object. each set of 5 values becomes one object. I am confused
>on the process of storing the object for retrieval later. basically I want
>to be able to click through the objects one at a time and later dump them
>back to a new file..
>Anybody have an idea of where I start.. Thanks in advance
There are two ways you can go about this:
1) You can write all 5 strings out to file (the reverse of how the objects
2) You can serialize the object or the whole list of objects to a file.
In order to serialize an instance of a class (a.k.a. an object) the class
definition must meet three criteria:
- the class must be public
- the class must implement the serializable interface
- if the class has a direct or indirect base class that is not serializable,
then that class must have a default constructor that requires no arguments.
Also, the derived class must take care of transferring the base class data
members to the stream.
Several of the classes in the Collections API (java.util.*) implement the
Serializable interface (Vector, HashTable, HashMap, HashSet, LinkedList,
etc.). You could store all the objects in one of these objects and serialize
the collection to a file.
Whether you are serializing a collection or a single object of a class that
implements the Serializable interface, the code is the same.
Here is an example:
FileOutputStream output = new FileOutputStream( "MyFile.store" );
ObjectOutputStream objOut = new ObjectOutputStream( output );
objectOut.writeObject( myObject );
Simply substitute the appropriate reference to the object you want to serialize
to the file.
DevX Java Pro
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL