My linux world » Java – Serializable

Java - Serializable


Important : require java 1.8 or greater to Serialize object from/to Base64.

Encode Object to base 64

// Write Serialized object to ByteArrayOutputStream :
ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
try(ObjectOutputStream oos = new ObjectOutputStream( baos )) {
  oos.writeObject( object );
}
 
// Encode to base 64 :
String result = Base64.getEncoder().encodeToString(baos.toByteArray());

Decode Serialized object as String

// Decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme.
byte [] data = Base64.getDecoder().decode( string );
 
// Get Serialized object :
Object object = null;
try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(  data ) )) {
  object  = ois.readObject();
}
catch (Exception e) {
  LOGGER.debug("error while reading serialized object",e);
}
return object;

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.