Object Serialized to Byte Array - Java java.io

Java examples for java.io:Serializable

Description

Object Serialized to Byte Array

Demo Code


import java.io.*;

public class Main{
    public static void main(String[] argv) throws Exception{
        Object o = "java2s.com";
        System.out.println(java.util.Arrays.toString(toByteArray(o)));
    }/*from w w w.j  a  v  a 2  s .  c  om*/
    public static byte[] toByteArray(Object o) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            return baos.toByteArray();
        } catch (IOException e) {
            LogHelper.warn("IOException during toByteArray");
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials