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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Object to Byte Array and back again?

Status
Not open for further replies.

Stevoie

Programmer
Jun 7, 2001
68
IE
anyone know how to convert any java object to a byte array then convert it back again?
thanx


StevoIE
 
See java API documentation :

- Write to an OutputStream an object whose class implements Serializable :

- Read from an InputStream an object whose class implements Serializable :

I've never used these classes, I think they are the right ones to use, anyway you must deal with the Serializable interface.

--
Globos
 
/**
*
* @param obj
* @return
* @throws java.io.IOException
*/
public byte[] convertObjectToBytes(Object obj) throws java.io.IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
return data;
}

/**
*
* @param obj
* @return
* @throws java.io.IOException
*/
public Object convertBytesToObject(byte[] bytes) throws java.io.IOException{

Object convertedObj = null;

ByteArrayInputStream bos = new ByteArrayInputStream(bytes);
ObjectInputStream oos = new ObjectInputStream(bos);
try{
convertedObj = (Object) oos.readObject();
}catch(Exception ex){
;
}
oos.close();
bos.close();

return convertedObj;
}

StevoIE
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top