Java Utililty Methods Serialize

List of utility methods to do Serialize

Description

The list of methods to do Serialize are organized into topic(s).

Method

StringserializeToString(Object o)
serialize To String
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(bytes);
stream.writeObject(o);
stream.flush();
return bytesToString(bytes.toByteArray());
voidserializeToSurefireDirectory(final Class testClass, final Object object)
Serializes the given object to the target/surefire-reports/ directory.
if (object == null) {
    return;
File file = new File("target");
if (!file.isDirectory() || !file.canWrite()) {
    System.err.println("Directory not found or read only: " + file.getAbsolutePath());
    return;
file = new File(file, "surefire-reports");
if (!file.exists() && !file.mkdir()) {
    System.err.println("Failed to create the output directory: " + file.getAbsolutePath());
    return;
file = new File(file, testClass.getName() + ".serialized");
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) {
    out.writeObject(object);
} catch (IOException e) {
    System.err.println(e);
    file.delete();
ObjectserializeUnserialize(Object ob)
Serializes and unserializes back an object to test whether it is correctly rebuilt (to be used in unit tests as sanity checks).
Serializable in = (Serializable) ob;
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream(byteOutStream);
outStream.writeObject(in);
ByteArrayInputStream byteInStream = new ByteArrayInputStream(byteOutStream.toByteArray());
ObjectInputStream inStream = new ObjectInputStream(byteInStream);
return inStream.readObject();