-
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
deaton
-
Re: Question on storing objects
"deaton" <deaton@primenet.com> 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
>
>deaton
Deaton,
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
were constructed.
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.
Happy Coding!
Cordially,
Kyle Gabhart
DevX Java Pro
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
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
|
Bookmarks