aspose file tools*
The moose likes Java in General and the fly likes Convert an Object to ByteArray Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Convert an Object to ByteArray" Watch "Convert an Object to ByteArray" New topic
Author

Convert an Object to ByteArray

Kunal Aher
Greenhorn

Joined: Apr 07, 2000
Posts: 20
Hi,
I plan to write an application where the Object is stored to some secondary storage. Can anyone suggest how we can convert an Object to a array of Bytes , so that I can store the Objects ?
Has anyone come across a similar problem , and if yes , what was the solution that was adopted ?
All ideas welcome .


Kunal
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Kunal,
Why not just Serialize the Object onto an ObjectOutputStream? You can write your objects to a file like this:

You can then later read them back like this:

Any object that you write to the File must implement the Serializable interface which has no methods and for that reason is called a tagging interface. Members declared transient will not be written to the File and there are some other issues that you may want to read about in the javadocs on ObjectInputStream and ObjectOutputStream.
Hope this helps,
Michael Morris


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Kunal Aher
Greenhorn

Joined: Apr 07, 2000
Posts: 20
Thanks for the reply .
But I am using the ATG Dynamo app server and their Repository API. It is a layer above the DB ( similar to JDO ) , and the method signature that they have provided to insert binary data takes a byte[]. There is no method like setObject that can be used. So the deadlock.

Regards
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
- Peter
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Kunal,
Well you can try something like this:
TestObject.java


ObjectByteArray.java


Hope this helps,
Michael Morris
Kunal Aher
Greenhorn

Joined: Apr 07, 2000
Posts: 20
Hi ,
Thanks . Its a great solution. I shall be trying
it out soon.
Let me share with you what I need this for. I am creating a few object , which will be the outcome of xml parsing , some DB lookups etc. But the data in them wont change regularly. So I though about this idea of storing those fully constructed objects in a secondary storage. And the next time I need those objects I will read them from the DB. Now the only thing left to do will be to compare the time to see if there are aany significant differences .The above soln. will allow me to go ahead with my idea.

Thanks once again .

Regards
[ March 04, 2003: Message edited by: Kunal Aher ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Convert an Object to ByteArray