Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading a vector to an inputstream

Status
Not open for further replies.

lowbk

Technical User
Nov 26, 2001
162
SG
hi guys, i would like to read in a vector as inputstream for some processing.
the current code i have is

ByteArrayOutputStream tmpbyte = new ByteArrayOutputStream();
ObjectOutputStream tmpobjstream = new ObjectOutputStream(tmpbyte);
tmpobjstream.writeObject(thevector);
tmpobjstream.flush();

byte[] tmpbytearray = tmpbyte.toByteArray();

ByteArrayInputStream tmpbytestream = new ByteArrayInputStream(tmpbytearray);
ObjectInputStream tmpobjstream = new ObjectInputStream(tmpbytestream);

it does work but it looks stupid having to deserialise the vector using outputstream then to byte[] then to inputstream. is there a better way?
 

A vector is serializable so you can read and write it
as an object using object input and output streams.
Howerver since vectors store plain vanilla objects
you must either maintain some index of the types so
you will be able to cast the contents correctly or
use some type of intraspection on the read side to
determine what type of object each element is.

//write side
ObjectOutputStream oo = new ObjectOutputStream(myOutputStream);
oo.writeObject(myVector);


// read side
ObjectInputStream oi=new ObjectInputStream(myInputStream);
Vector v=(Vector)oi.readObject();
for(int i=0;i<v.size();i++)
{
Class c=v.elementAt(i).getClass();
System.out.println(&quot;The objects type is &quot;+c.getName());
}

Using the class object you can build a picture of the
contents of objects of unknown types with methods like
getConstructors() and getMethods().
I've only used this type of approach where all the classes
that would be read implemented an agreed upon interface
that defined an entry point. This is only safe in trusted
environments.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top